【问题标题】:Is the resource of a shadowed variable binding freed immediately?阴影变量绑定的资源是否立即释放?
【发布时间】:2015-05-18 13:10:30
【问题描述】:

根据 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?

【问题讨论】:

  • 绑定只是一个值的名称,将名称指向其他东西不会影响值本身,它会按照其他方式存在。

标签: rust


【解决方案1】:

不,它不会立即释放。让代码自己告诉我们:

struct Foo(u8);

impl Drop for Foo {
    fn drop(&mut self) {
        println!("Dropping {}", self.0)
    }
}

fn main() {
    let a = Foo(1);
    let b = Foo(2);

    println!("All done!");
}

输出是:

All done!
Dropping 2
Dropping 1

对我来说,这在您将变量转换为某种引用但不关心原始值的情况下会派上用场。例如:

fn main() {
    let msg = String::from("   hello world   \n");
    let msg = msg.trim();
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-12-14
    • 2015-05-14
    • 1970-01-01
    • 1970-01-01
    • 2021-11-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多