根据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?
Run Code Online (Sandbox Code Playgroud)
不,它不会立即释放.让Rust 告诉我们自己:
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!");
}
Run Code Online (Sandbox Code Playgroud)
输出是:
All done!
Dropping 2
Dropping 1
Run Code Online (Sandbox Code Playgroud)
对我来说,在将变量转换为某种引用但不关心原始变量的情况下,这已派上用场了.例如:
fn main() {
let a = Foo(1);
let a = &a;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
81 次 |
| 最近记录: |