-1

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?

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
0xsegfault
  • 2,899
  • 6
  • 28
  • 58
  • It is preferred to post separate questions instead of combining your questions into one. That way, it helps the people answering your question as well as others hunting for one of your questions. – Shepmaster Jan 06 '19 at 23:44

1 Answers1

1

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.

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
Brady Dean
  • 3,378
  • 5
  • 24
  • 50
  • so its creating new variables? what about 2? if its meant to be mututable then by definition its type isnt fixed at compile time so heap? – 0xsegfault Jan 06 '19 at 23:42
  • In example 2 there is only 1 variable on the stack. Its value is changed with each assignment. – Brady Dean Jan 06 '19 at 23:45
  • 4
    @Data_Kid "if its meant to be mututable then by definition its type isnt fixed" What is your definition of mutability that that would follow from the definition? Mutable variables still have a fixed type in Rust (and the vast majority of other statically typed languages). – sepp2k Jan 06 '19 at 23:45