Search code examples
rustshadowing

Shadowing in without "let"


From my understanding, shadowing in Rust allows you to use the same variable by using let and re-declaring the variable e.g.

let x = 5;

let x = x + 1;

let x = x * 2;

println!("The value of x is: {}", x);

but, if you make the variable mutable, doesn't that mimic shadowing e.g.:

let mut x = 5;
println!("The value of x is: {}", x);
x = 6;
println!("The value of x is: {}", x);
 x = 7;
println!("The value of x is: {}", x);

In example 1 & 2, where is the variable stored, in the stack or heap?


Solution

  • All values in your example are stored on the stack. In example 1, a new value is pushed onto the stack for each let statement.

    It looks like you got the example from The Rust Programming Language. Maybe read this paragraph again for emphasis:

    The other difference between mut and shadowing is that because we’re effectively creating a new variable when we use the let keyword again, we can change the type of the value but reuse the same name.