頭條地址: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 協議》,轉載必須註明作者和本文連結