美文网首页RUST编程
Rust 编程视频教程(进阶)——012_2 提前调用 drop

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

作者: 令狐壹冲 | 来源:发表于2020-02-07 21:20 被阅读0次

视频地址

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

源码地址

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

讲解内容

通过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

相关文章

网友评论

    本文标题:Rust 编程视频教程(进阶)——012_2 提前调用 drop

    本文链接:https://www.haomeiwen.com/subject/yoerxhtx.html