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 协议》,转载必须注明作者和本文链接
推荐文章: