Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

The Drop trait is implemented by types that have resources to free when an instance goes out of scope. For instance the Vec handles an array stored onto the heap. Vec implements the Drop trait, so that when a Vec variable goes out of scope the heap memory is freed.

To show how the Drop trait works, we create a Foo structure with just an integer field:

We then implement the Drop trait for Foo with a fake drop() method that just prints a message:

If we create a Foo object inside a scope, we see the call to the drop() method at the end of the scope:

x: Foo { n: -6 }
Dropping object Foo with value -6.
()

Using the drop() function we can trigger the cleaning of a variable before it goes out of scope. We must not call the drop() method of the object directly, because we need to disable the automatic drop at the end of the scope. Calling the drop() function will disable the automatic drop:

Dropping object Foo with value 18.
Dropping of y has been done.
()