Rust Lang

Rust Mutability

Mutability refers to the ability to update or modify something. In Rust, this means the ability to change the value of a type after declaration.

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:

fn main() {
    let var = 10;
    var = 100;

If we run the code above, the rust compiler will fail and return an error as shown:

error[E0384]: cannot assign twice to immutable variable `var`

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.


fn main() {
    let mut var = 10;
    var = 100;

With the mut keyword, we can change the value of the variable var from 10 to 100.


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:

const PI: f64 = 3.14159

Attempting to set a constant variable as mutable will result in an error:

const mut PI: 64 = 3.14159

The above code should return:

error: const globals cannot be mutable

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 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:

fn main() {
    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.


This was a short tutorial covering variables and mutability in Rust. Check the documentation to explore further.

About the author

John Otieno

My name is John and am a fellow geek like you. I am passionate about all things computers from Hardware, Operating systems to Programming. My dream is to share my knowledge with the world and help out fellow geeks. Follow my content by subscribing to LinuxHint mailing list