2.21 Drop

There’s one trait contained by Rust’s standard library in particular, that is useful whenever you need to free resources at the end of a scope. The Drop trait, does whatever you define it to upon going out of scope. This means that you can have a Person struct, who gets mad when they go out of scope and ultimately gets killed.

Implementation

We’ll start off by creating a Person struct, even though this to be fair is more useful when you need your structs to free resources that might stay stuck in them otherwise:

struct Person
{
    beard_length: i32
}

fn main()
{
    let person = { beard_length: 200 };
}

Should the i32 defining the length of this person’s beard be in meters, this person sure has a long beard! But we still want him to get mad upon being executed. We can achieve this by implementing the Drop trait unto Person:

impl Drop for Person
{
    fn drop(&mut self)
    {
        println!("Et tu, Brute?");
    }
}

Finally, upon executing this program:

Et tu, Brute?

But, why?

Let us have a look at that main function of ours:

fn main()
{
    // ‘person’ enters scope
    let person = { beard_length: 200 };

    // ‘person’ goes out of scope
}

Since Person has the Drop trait implemented for them, the drop method inside the implementation is called, ultimately responding to all instructions we give it. To be Caesar, this person sure listens well to instructions.

Exercises

  • Repeat the development of this program yourself, making sure to understand and memorize everything it does and as to why it does it.

Moreover

Understanding the Drop trait will prove to be immensely useful in the future of your Rust programming career. Whenever you have a stubborn resource that for some reason does not want to get destroyed upon going out of scope, call you friend Drop! Your friend Drop never lets you down.

Format