From Rust Community Wiki
Jump to navigation Jump to search

A destructor is a function that is run when a value is destroyed. Destructors are often used to free resources (e.g. heap memory) that are no longer required when a value is destroyed.

Values are destroyed when they are dropped, which usually happens when they go out of scope (at the end of the enclosing curly braces {}). Static items are never dropped. Most types don't have a destructor; when they are dropped, nothing happens.

In Rust, destructors are defined by implementing the DropThis links to official Rust documentation trait. Note that even types that don't implement Drop can have a destructor. For example, Option<Box<()>> doesn't implement Drop, but it has a destructor that deallocates the inner Box, if present. This is called a drop glue.

Example[edit | edit source]

struct Foo;

impl std::ops::Drop for Foo {
    fn drop(&mut self) {
        println!("Foo was dropped.");

This prints "Foo was dropped." every time the a Foo instance is dropped.

Use cases[edit | edit source]


Impact on non-lexical lifetimes[edit | edit source]