走进Rust:Drop trait

Rust大约 601 字

实现Drop

实现Drop trait用于手动清理某个值,例如锁。

struct CustomSmartPointer {
    data: String,
}

impl Drop for CustomSmartPointer {
    fn drop(&mut self) {
        println!("Dropping CustomSmartPointer with data `{}`!", self.data);
    }
}

调用 drop 方法

使用std::mem::drop函数

fn main() {
    let c = CustomSmartPointer { data: String::from("some data") };
    println!("CustomSmartPointer created.");
    drop(c);
    println!("CustomSmartPointer dropped before the end of main.");
}

输出

CustomSmartPointer created.
Dropping CustomSmartPointer with data `some data`!
CustomSmartPointer dropped before the end of main.
阅读 59 · 发布于 2020-08-25

————        END        ————

扫描下方二维码关注公众号和小程序↓↓↓

昵称:
随便看看换一批