根据Rust书,"当绑定超出范围时,他们绑定的资源将被释放"。这也适用于阴影吗?
示例:
fn foo() {
let v = vec![1, 2, 3];
// ... Some stuff
let v = vec![4, 5, 6]; // Is the above vector freed here?
// ... More stuff
} // Or here?
答案 0 :(得分:6)
不,它不会立即释放。让我们做Rust tell us itself:
struct Foo(u8);
impl Drop for Foo {
fn drop(&mut self) { println!("Dropping {}", self.0) }
}
fn main() {
let a = Foo(1);
let a = Foo(2);
println!("All done!");
}
输出结果为:
All done!
Dropping 2
Dropping 1
对我来说,在将变量转换为某种引用但不关心原始变量的情况下,这已派上用场了。例如:
fn main() {
let a = Foo(1);
let a = &a;
}