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?
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 eg here with optimisations enabled it'll constant fold everything and directly print the constant 12
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.