← Back to Rust Course | Chapter 5: Ownership | Lesson 5 of 6

Scope and the Drop Trait

When a value's box of usefulness (its scope) ends, Rust automatically cleans it up for you -- no need to ask.

Automatic Cleanup at End of Scope

Every value's owner has a scope, and when that scope ends, Rust automatically runs cleanup code for the value, freeing any associated memory without any explicit action from you.

Example: Automatic Cleanup at End of Scope

markup
fn main() {
    let message = String::from("cleaned up automatically");
    println!("{}", message);
} // message is dropped here

Implementing Drop

You can implement the Drop trait for your own struct to run custom cleanup logic, such as printing a message, right when a value of that type goes out of scope.

Example: Implementing Drop

markup
struct Connection {
    name: String,
}

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

fn main() {
    let _conn = Connection { name: String::from("db") };
    println!("Using connection");
}

Drop Order Is Reverse of Declaration

When multiple values go out of scope together, Rust drops them in the reverse order they were declared, similar to unwinding a stack.

Example: Drop Order Is Reverse of Declaration

markup
struct Announcer(i32);

impl Drop for Announcer {
    fn drop(&mut self) {
        println!("Dropping {}", self.0);
    }
}

fn main() {
    let _first = Announcer(1);
    let _second = Announcer(2);
    println!("Both created; watch the drop order below");
}

Forcing an Early Drop

Sometimes you want a value cleaned up before its scope naturally ends. Since you cannot call .drop() directly, the standard library provides std::mem::drop to consume and drop a value early.

Example: Forcing an Early Drop

markup
struct Resource;

impl Drop for Resource {
    fn drop(&mut self) {
        println!("Resource released early");
    }
}

fn main() {
    let res = Resource;
    println!("About to release early");
    drop(res);
    println!("Released; rest of main continues");
}
Common Mistakes
  1. Manually trying to free or clean up a value yourself instead of trusting Rust's automatic Drop behavior.
  2. Assuming Drop runs in the order variables were created -- it actually runs in reverse order of declaration within a scope.
  3. Implementing a custom Drop and also calling .clone() unnecessarily, not realizing Drop only runs once per owned value automatically.
Chapter Summary
  • When a value's owner goes out of scope, Rust calls the Drop trait's drop method automatically to clean it up.
  • Values are dropped in the reverse order they were declared within a scope.
  • You can implement a custom Drop for your own types to run cleanup code, like closing a resource.
  • You cannot call .drop() manually -- Rust prevents this to avoid double-free bugs; use std::mem::drop instead if needed.
🔒

Chapter Quiz — Complete all 6 topics to unlock

0/6 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.