Drop

This is the trait we've been referring to quite a few times which does all the magic of automatically freeing up the resources that are used when a value goes out of scope. The Drop trait is akin to 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. The method takes in a &mut self as parameter. Freeing of values with drop is done in last in, first out. That is, whatever was constructed the last, gets destructed first. The following code illustrates this:

// drop.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(),
};
}

The output is as follows: 

The drop method is an ideal place for you to put any cleanup code for your own structs, if needed. It's especially handy for types where the cleanup is less clearly deterministic, such as when using reference counted values or garbage collectors. When we instantiate any Drop implementing value (any heap allocated type), the Rust compiler inserts drop method calls after every end of scope, after compilation. So, we don't need to manually call drop on these instances. This kind of automatic reclamation based on scope is inspired by the RAII principle of C++.

..................Content has been hidden....................

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