Swaroop Maddu
Swaroop Maddu

Reputation: 4854

Rust Shadowing memory management

fn main() {
  let x = 5;
  let x = x + 1;
  let x = x * 2;
  println!("The value of x is: {}", x);
}

When your code calls a function the function’s local variables get pushed onto the stack. When the function is over, those values get popped off the stack.

During shadowing what happens to the variable x that we declared first? Do we overwrite the memory location of x or we create a new x at another location in the stack?

Upvotes: 0

Views: 185

Answers (1)

Masklinn
Masklinn

Reputation: 42292

Do we overwrite the memory location of x or we create a new x at another location?

Semantically, a new memory location is created and "x" now points to that location. Depending on the optimisations being applied, the compiler could reuse the memory location instead. Or not even allocate a memory location at all, really e.g. here with optimisations enabled it'll constant fold everything and directly print the constant 12.

Upvotes: 4

Related Questions