Drop

When a data type has the Drop trait, the program will call the drop function for values of that type immediately before their lifetimes end. That's how Rc, Mutex, RefCell, and so on are able to keep track of how many borrows their contained value has.

The drop function is called before the data value's lifetime ends, so we don't have to worry about it being an invalid reference. Also, we don't have to worry about manually cleaning up the contained values for our data type, because they will be automatically dropped themselves after our drop function is finished. All we need to do is handle whatever special case led us to implement Drop in the first place.

We can't directly call the drop function, because that would be an extremely good way to make a mess. There is a std::mem::drop function we can use that consumes a data value and drops it for us, if we need to trigger this at a specific time.

Implementing Drop looks like this:

pub enum DropExample {
Good,
Bad,
}

impl Drop for DropExample {
fn drop(&mut self) {
match self {
DropExample::Good => println!("Good DropExample dropped"),
DropExample::Bad => println!("Bad DropExample dropped"),
};
}
}
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.12.162.37