O'Reilly logo

Mastering Rust by Vesa Kaihlavirta

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

The Drop trait

The Drop trait is what you would call an object destructor method in other languages. It contains a single method drop, which gets called when the object goes out of scope. This is done in a strict order: last in, first out. That is, whatever was constructed the last, gets destructed the first. For example:

// drops.rs struct Character {     name: String } impl Drop for Character {     fn drop(&mut self) {         println!("{} went away", self.name)     } } fn main() {     let steve = Character { name: "Steve".into() };     let john = Character { name: "John".into() }; } 

And the output is as follows: 

This mechanism is where you should put the ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required