Rust 阴影内存管理
Rust Shadowing memory management
fn main() {
let x = 5;
let x = x + 1;
let x = x * 2;
println!("The value of x is: {}", x);
}
当您的代码调用函数时,函数的局部变量会被压入堆栈。当函数结束时,这些值会从堆栈中弹出。
在隐藏期间,我们首先声明的变量 x 发生了什么?我们是覆盖 x 的内存位置还是在堆栈中的另一个位置创建一个新的 x?
Do we overwrite the memory location of x or we create a new x at another location?
从语义上讲,创建了一个新的内存位置,“x”现在指向该位置。根据所应用的优化,编译器 可以 重用内存位置。或者甚至根本不分配内存位置,例如这里启用了优化,它将不断折叠所有内容并直接打印常量 12
.
fn main() {
let x = 5;
let x = x + 1;
let x = x * 2;
println!("The value of x is: {}", x);
}
当您的代码调用函数时,函数的局部变量会被压入堆栈。当函数结束时,这些值会从堆栈中弹出。
在隐藏期间,我们首先声明的变量 x 发生了什么?我们是覆盖 x 的内存位置还是在堆栈中的另一个位置创建一个新的 x?
Do we overwrite the memory location of x or we create a new x at another location?
从语义上讲,创建了一个新的内存位置,“x”现在指向该位置。根据所应用的优化,编译器 可以 重用内存位置。或者甚至根本不分配内存位置,例如这里启用了优化,它将不断折叠所有内容并直接打印常量 12
.