Rust, Software Development

Rust – Use The Drop Trait To Run Codes After Instance is Destroyed

Rust Environment Variables Display struct content

In Rust, we can run codes when an instance is about to be destroyed. This post briefly demonstrates how to perform just that.

Using Drop Trait

To achieve our goal, we need to use the Drop trait.

Rust Codes

We have these initial codes with implemented Drop traits.

First Output

Given the output below and considering the concept of ownership and how it works in Rust, where did the drop(&mut self)  function execute – in main()  or another_func1()? At first glance, it appears the instance was destroyed when main()  finishes execution.

Second Output

Now we modified the previous codes to these.


This final output proves that the instance was “destroyed” in the another_func1()  function. Now, why is that? See What is Ownership?

Third Output

Now how do we make the code destroy out instance within the main function? In the previous codes, we let the function another_func1()  take ownership of a resource. This time we let another_func1()  borrow a resource that is still owned by the main()  function.

We have the modified codes.


As we can see, the resource was destroyed after the println!()  statement in the main()  function.

You Might Also Like