[英]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?在隐藏期间,我们首先声明的变量 x 会发生什么? Do we overwrite the memory location of x or we create a new x at another location in the stack?
我们是覆盖 x 的内存位置还是在堆栈中的另一个位置创建一个新的 x?
Do we overwrite the memory location of x or we create a new x at another location?
我们是覆盖 x 的内存位置还是在另一个位置创建一个新的 x?
Semantically, a new memory location is created and "x" now points to that location.从语义上讲,创建了一个新的内存位置,“x”现在指向该位置。 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
.或者甚至根本不分配内存位置,例如在启用优化的情况下,它会不断折叠所有内容并直接打印常量
12
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.