Chapter 3, Section 3.1 immutable x

I just finished learning that, unless I make a variable mutable, it's value does not change and then in the shadowing example the first two lines are:

 let x = 5;

    let x = x + 1;

If x is not mutable, how can x be changed. I understand shadowing by changing a variable inside an block of code temporarily. But in that example, x is NOT mutable. Can anyone explain this to me?

This works because the author used 'let' again. This creates a new variable with the same name as the old one (shadowing). Without that second let you would receive the compiler error you expect.

experiment by declaring it mutable the first time then the shadow declaration can turn the mut off:

let mut x = 5;
let x = x + 1;
x = x + 1; //compiler errors here due to 'cant change immutable x.'

1 Like

The difference to C-style shadowing is that Rust supports shadowing even in the middle of the block. But it does not mutate the variable, just creates a new one. It is the same as:

let x = 5;
    let x = x + 1;
    // Lots of code...

Here's a version that may help show that each let x allocates a new variable, and that the old one may or may not go out of scope (though the old one is no longer accessible by name): playground

edit: another version, showing it on a non-Copy type: playground

Thank each of you. I missed the part where it builds a new variable that is no longer available. Thank each of you for expanding on what is really happening. These are all good and helped a lot. Thank YOU!