drop-trait Drop trait类似于其他语言中的析构函数,值离开作用域的时候执行函数的代码 123456789101112131415161718192021222324252627struct Dog {name: String, //count: i32,}impl Drop for Dog { fn drop(&mut self) { //走的时候需要释放Dog,所以是mut println!("Dog {} leave",self.name); //self.count -= 1; }}fn main() { let a = Dog{name: String::from("wangcai")}; {let b = Dog{name: String::from("dahuang")}; println!("0++++++++++++++++++"); } println!("1++++++++++++++++++");}//首先释放的是b,然后是a//0++++++++//Dog dahuang leave//1++++++++//Dog wangcai leave drop的提前释放 12345678910111213141516171819202122232425struct Dog { name: String, }impl Drop for Dog { fn drop(&mut self) { println!("{} leave",self.name); } }fn main() { let a = Dog{name: String::from("wangcai")}; let b = Dog{name: String::from("dahuang")}; //dahuang leave //wangcai leave //可以看出值在栈上 //如果提前leave //报错,drop不允许显式调用,正确写法是 //b.drop(); drop(b); drop(a); }