Immutability of variables

I started learning rust a couple days ago and have a question regarding immutability of variable.

Why does the following code run successfully?

fn main() {
    let x = 5;
    println! ("Value of x is {}", x);
    let x = 6;
    println! ("Value of x is {}", x);
}

Output:
Value of x is 5
Value of x is 6

1 Like

You created an "x" and gave it the value "5"

Then you created another "x" and gave it the value "6"

That did not mutate the original "x", it created a new, different "x". That first "x" is no longer visible in the scope of your code. This is known as "shadowing".

If you want to mutate the original "x" you would simply write the assignment "x = 6" instead.

4 Likes

Thanks.
Yes, that helps. I also read about the concept of Shadowing in Rust rn.

1 Like

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.