Open In App

Rust – The mut Modifier

Last Updated : 29 Sep, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

In Rust, we have a concept of mut modifier.  A mutable variable is a variable used for binding values to variable names. Mut variables in Rust have specific use cases i.e. used in situations where we need to bind values into variables.

For declaring a variable as mutable, we use the mut keyword as variables are immutable (by default) in Rust.

Mutability is an extremely helpful concept that improves code readability in Rust and is particularly useful for declaring any variable as mut implies that by changing the value of the variable, we would be changing other parts of the code.  

Understanding mut keyword with the two examples:

Example 1: 

Rust




// Rust program for mut modifier
  
fn main() {
    let mut _num = 10;
    println!("The value of num before using mut keyword: {_num}");
    _num = 20;
    println!("The value of num after using mut keyword : {_num}");
}


Output:

 

In this example, we initially declare a variable (_num) as mut and initialize it to 10. After removing the mut keyword we can see that now we can change and reinitialize it.

Now another example, we see the variables are bound immutably by default and are overridden by using the mut modifier. 

Example 2: 

Rust




// Rust program for the variables 
// bound immutably by default and
// are overridden by using the mut modifier. 
fn main() {
    let _immutable_GFG_variable = 10;
    let mut mutable_GFG_variable = 20;
  
    println!("Before mutation: {}", mutable_GFG_variable);
  
    mutable_GFG_variable += 5;
  
    println!("After mutation: {}", mutable_GFG_variable);
  
    _immutable_GFG_variable += 5;
}


Output:

 

We can clearly see that we cannot reassign twice to the immutable variable( `_immutable_GFG_variable’). To rectify this error, we need to bind the variable by making it mut.



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads