Rust, Software Development

Rust – Drop Trait To Run Codes After Instance is Destroyed

With the Rust Drop trait and destructor, we can run codes before Rust destroys an instance. This post shows how to perform just that.

Sample Rust Codes Using Drop Trait

To achieve our goal, we need to use the Drop trait. We have these initial codes with implemented Drop traits. While the codes are simple, they exhibit behavior that works implicitly. Meaning, we do not run any destructor. Instead, we only implement the Drop trait and let Rust run the drop function.

First, we define a struct. In our case, we have the DatabaseConnection struct, which is a plain struct. Therefore, it cannot connect to a database.

Testing Rust With struct Instances

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 that Rust has destroyed the instance when main()  finishes execution.

Now, let us modify the previous codes to ascertain when the Rust runs the drop function. We would expect it to happen before the main function completes.

When we run the codes, we get the following out.

The output proves that the instance was “destroyed” in the another_func1()  function. Now, why is that? It has something to do with ownership in Rust. When the function executes, it accepts an instance of a struct. As a result, a change of ownership happens from the main function to the another_func1() function. By the time it completes its execution before the main function does, Rust destroys the struct instance.

Now how do we make the code destroy our 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 still owned by the main()  function.

Hence, we the modified codes as shown below.

The codes generate the following output.

run codes before instance destroy

As we can see, Rust ran codes to destroy a struct instance after the println!()  statement in the main()  function. The destruction happened because we used the Rust Drop trait and let the destructor mechanism in Rust work.

Loading

Got comments or suggestions? We disabled the comments on this site to fight off spammers, but you can still contact us via our Facebook page!.


You Might Also Like