Rust 编程视频教程(进阶)——012_2 提前调用 drop

视频地址

头条地址:https://www.ixigua.com/i677586170644791348...
B站地址:https://www.bilibili.com/video/av81202308/

源码地址

github地址:https://github.com/anonymousGiga/learn_rus...

讲解内容

通过std::mem::drop提早丢弃值。当需要提前进行清理时,不是直接调用drop方法,而是调用是std::mem::drop方法,例如如下:

struct Dog {
    name: String,
}

//下面为Dog实现Drop trait
impl Drop for Dog {
    fn drop( &mut self ) {
        println!("Dog leave");
    }
}

fn main() {
    let a = Dog { name: String::from("wangcai")};
    let b = Dog { name: String::from("dahuang")};
    //a.drop();//错误,不能直接调用drop
    drop(a);//正确,通过std::mem::drop显示清理
    println!("At the end of main");
}

上述例子打印的顺序将是:

Dog leave //调用drop(a)的打印
At the end of main
Dog leave
本作品采用《CC 协议》,转载必须注明作者和本文链接
令狐一冲
讨论数量: 0
(= ̄ω ̄=)··· 暂无内容!

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!
文章
255
粉丝
120
喜欢
308
收藏
128
排名:335
访问:2.8 万
私信
所有博文
社区赞助商