0:00
/
0:00
Transcript

Implementing the Drop Trait

How to add cleanup code in Rust

Code on GitHub: https://github.com/caveofprogramming/rust/

If a Rust type implements the Drop trait, the drop method of any object of that type will be called automatically when the variable that owns it goes out of scope.

This can be used for cleanup, e.g. terminating database connections, freeing memory.

Here’s a struct called Data which stores a single value.

We can implement the Drop trait like this:

Here I’ve made the drop function just output some text.

Now drop() is called whenever the owner of any object of type Data goes out of scope.

For example, the following code outputs Dropping 0, because here the owner of the Data struct immediately goes out of scope right after it’s created, at the closing bracket.

As a precaution against cleanup code being called twice, the drop method cannot be called directly, but you can invoke it using the std::mem::drop function (which is part of the prelude so no need for an import).

Discussion about this video