丢弃
Drop
trait 只有一种方法:drop
,当对象超出作用域时会自动调用该方法。 Drop
trait 的主要用途是释放实现者实例拥有的资源。
Box
、Vec
、String
、File
和 Process
都是实现 Drop
trait 以释放资源的类型的示例。 Drop
trait 也可以为任何自定义数据类型手动实现。
以下示例在 drop
函数中添加了打印到控制台的功能,以便在调用该函数时发出通知。
struct Droppable { name: &'static str, } // This trivial implementation of `drop` adds a print to console. impl Drop for Droppable { fn drop(&mut self) { println!("> Dropping {}", self.name); } } fn main() { let _a = Droppable { name: "a" }; // block A { let _b = Droppable { name: "b" }; // block B { let _c = Droppable { name: "c" }; let _d = Droppable { name: "d" }; println!("Exiting block B"); } println!("Just exited block B"); println!("Exiting block A"); } println!("Just exited block A"); // Variable can be manually dropped using the `drop` function drop(_a); // TODO ^ Try commenting this line println!("end of the main function"); // `_a` *won't* be `drop`ed again here, because it already has been // (manually) `drop`ed }