0

Rust – Run Codes When Instance is Destroyed

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 Drop  trait.

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.

Output

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 which is still owned by the main()  function.

We have the modified codes.

Output

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

Karl San Gabriel

Karl San Gabriel

Professional Software Developer