Language
日本語
English

Caution

JavaScript is disabled in your browser.
This site uses JavaScript for features such as search.
For the best experience, please enable JavaScript before browsing this site.

Rust Dictionary

  1. Home
  2. Rust Dictionary
  3. Drop Trait / Scope and Deallocation

Drop Trait / Scope and Deallocation

The Drop trait is Rust's mechanism for implementing the RAII (Resource Acquisition Is Initialization) pattern. It automatically runs cleanup code when a value goes out of scope.

Syntax

// Implementing the Drop trait
impl Drop for TypeName {
    fn drop(&mut self) {
        // Called automatically when the value goes out of scope.
    }
}

// Early deallocation (use the std::mem::drop function)
drop(variable);

Overview

ItemDescription
Drop::drop()A method called automatically when a value goes out of scope. You cannot call it directly.
drop() functionTakes ownership of a value and immediately ends its scope, using the standard library's drop() function.
Drop orderVariables are dropped in reverse order of declaration — the last declared is dropped first.
RAII patternUsed to manage resources such as file handles, locks, and network connections.

Example

struct Resource {
    name: String,
}

impl Drop for Resource {
    fn drop(&mut self) {
        println!("Dropped: {}", self.name);
    }
}

fn main() {
    let r1 = Resource { name: String::from("Resource 1") };
    {
        let r2 = Resource { name: String::from("Resource 2") };
        let r3 = Resource { name: String::from("Resource 3") };
        println!("Inside the inner scope");
    } // r3 and r2 are dropped in that order (reverse of declaration).

    println!("Back in the outer scope");

    let r4 = Resource { name: String::from("Resource 4") };
    drop(r4); // Drop r4 early.
    println!("r4 has been dropped");
} // r1 is dropped here.

Details

The Drop trait can manage not just memory, but any kind of resource — including closing files, releasing Mutex locks, and disconnecting network connections. Many types in Rust's standard library (such as File and MutexGuard) implement Drop.

You cannot call Drop::drop() directly. If you need to drop a value early, always use the standard library's drop() function instead.

The Copy trait and the Drop trait cannot coexist on the same type. If you want to implement Copy, see Clone / Copy トレイト.

If you find any errors or copyright issues, please .