Let us discuss mutability and how to use it in Rust.
By default, all variables in Rust are immutable. This means you cannot change the value after initialization.
For example:
let var = 10;
var = 100;
}
If we run the code above, the rust compiler will fail and return an error as shown:
Although variables are immutable by default, it’s useful to have a mutable variable. We can make a variable mutable using the mut keyword in front of the variable name. This tells the compiler that the other parts of the program can modify the variable.
Example:
let mut var = 10;
var = 100;
}
With the mut keyword, we can change the value of the variable var from 10 to 100.
Constants
Constants are closely similar to immutable variables. Hence, once a value is declared, you cannot change the value in other parts of the program.
What makes constants different from other immutable variables is that they are declared using the const keyword instead of let and you cannot make them mutable.
For example:
Attempting to set a constant variable as mutable will result in an error:
The above code should return:
Rust prevents you from setting a value as mutable. Keep in mind that the value of a constant variable should be a constant expression and not a result of a computed expression. Check our tutorial on rust constants to learn more.
Shadowing
Shadowing refers to a technique where a variable is “overwritten” by another value with the same name.
For example, you can have a variable called var with the value 10. You can then redeclare that variable with the same name and assign it a value of 100. When this happens, we say that the second variables shadow the first.
Take the example below:
let var = 10;
{
let var = 100;
}
}
In the example above, we have the variable var that holds the value 10. We then create an inner scope that shadows the variable in the inner scope.
Keep in mind that shadowing is not similar to setting a variable as mutable.
Conclusion
This was a short tutorial covering variables and mutability in Rust. Check the documentation to explore further.