- Drop
- drop
Drop - destructor
- Implement the Drop trait
- By default when there is a panic! Rust will unwind the allocated memory and it will call the drop method on each object it encounters. We can set the panic compiler option to 'abort' in the Cargo.toml file to make Rust exit without unwinding. This will make shutting down the program faster, but in this case the drop methods will not be called.
examples/struct/drop-demo/src/main.rs
#![allow(dead_code, unused_variables)] struct HasDrop { name: String, } impl Drop for HasDrop { fn drop(&mut self) { println!("Dropping HasDrop! {}", self.name); } } struct HasTwoDrops { one: HasDrop, two: HasDrop, } impl Drop for HasTwoDrops { fn drop(&mut self) { println!("Dropping HasTwoDrops!"); } } fn main() { let hd = HasDrop { name: String::from("Foo"), }; let _hd = HasTwoDrops { one: HasDrop { name: String::from("first"), }, two: HasDrop { name: String::from("second"), }, }; calc(3, 0); } fn calc(x: i32, y: i32) -> i32 { if y == 0 { panic!("oups"); } x / y }
examples/struct/drop-demo/Cargo.toml
[package] name = "drop-demo" version = "0.1.0" edition = "2021" [dependencies] #[profile.dev] #panic = 'abort' #[profile.release] #panic = 'abort'