Search code examples
rustmutability

Why does changing a variable without a "mut" not throw a mutability error?


I was reading the Scopes and Shadowing section of Rust By Example and was confused about the mutability of variables. In this example there is a variable defined to a value of 1.

let long_lived_binding = 1;

It is later changed to

let long_lived_binding = 'a';

To my understanding, if you wanted to change a variable you needed to put the keyword mut in front of it. For example let mut long_lived_binding = 1; Why does the given example in Rust By Example not throw a mutability error?


Solution

  • Mutability prevents modification of a variable, but it will not prevent you introducing a variable with same name using let. The difference is subtle but noticeable. Shadowing can change the type of value. Mutability can't.

    Shadowing:

    let x = 2;
    let x = "String";
    

    Mutability:

    let x = 2;
    x = 3; // will not compile because the variable that's immutable was assigned twice.
    
    let mut x = 2;
    x = 3;
    x = "String"; // will not compile because you changed the type.
    

    playground link