我在 Rust 书中看到可以用相同的名称定义两个不同的变量:
let hello = "Hello";
let hello = "Goodbye";
println!("My variable hello contains: {}", hello);
打印出来:
My variable hello contains: Goodbye
第一个你好会发生什么?它得到释放了吗?我如何访问它?
我知道将两个变量命名为相同的变量是不好的,但如果因为我在下面 100 行声明它而意外发生,那将是一个真正的痛苦。
最佳答案
Rust does not have a garbage collector .
Does Rust free up the memory of overwritten variables?
是的,否则就是内存泄漏,这将是一个非常糟糕的设计决策。重新分配变量时释放内存:
struct Noisy;
impl Drop for Noisy {
fn drop(&mut self) {
eprintln!("Dropped")
}
}
fn main() {
eprintln!("0");
let mut thing = Noisy;
eprintln!("1");
thing = Noisy;
eprintln!("2");
}
0
1
Dropped
2
Dropped
what happens with the first hello
是shadowed .
除了您无法再访问它之外,变量引用的数据没有任何“特殊”变化。当变量超出范围时它仍然被丢弃:
struct Noisy;
impl Drop for Noisy {
fn drop(&mut self) {
eprintln!("Dropped")
}
}
fn main() {
eprintln!("0");
let thing = Noisy;
eprintln!("1");
let thing = Noisy;
eprintln!("2");
}
0
1
2
Dropped
Dropped
另见:
I know it would be bad to name two variables the same
这不是“坏”,而是设计决定。我会说像这样使用阴影是个坏主意:
let x = "Anna";
println!("User's name is {}", x);
let x = 42;
println!("The tax rate is {}", x);
像这样使用阴影对我来说是合理的:
let name = String::from(" Vivian ");
let name = name.trim();
println!("User's name is {}", name);
另见:
but if this happens by accident because I declare it 100 lines below it could be a real pain.
不要有大到你“不小心”做某事的功能。这适用于任何编程语言。
Is there a way of cleaning memory manually?
您可以调用drop
:
eprintln!("0");
let thing = Noisy;
drop(thing);
eprintln!("1");
let thing = Noisy;
eprintln!("2");
0
Dropped
1
2
Dropped
然而,作为oli_obk - ker points out ,变量占用的栈内存直到函数退出才会释放,只有变量占用的资源。
所有关于 drop
的讨论都需要展示它的(非常复杂的)实现:
fn drop<T>(_: T) {}
What if I declare the variable in a global scope outside of the other functions?
全局变量永远不会被释放,即使您可以创建它们来开始。
关于memory-management - Rust 会释放被覆盖变量的内存吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48227347/