Course contentsShow
← Rust
Lesson 353 of 1,9104. Lifetimes and Advanced OwnershipFree lesson

Invoking Drop Explicitly

Control object lifecycle termination manually using standard library utilities.

In this lesson, you will learn how to manually trigger an object's cleanup logic before it naturally reaches the end of its scope.

The RAII Default

In Rust, the Drop trait automatically cleans up resources when a variable goes out of scope. This is the bedrock of the RAII (Resource Acquisition Is Initialization) pattern. Usually, you never need to call drop yourself; the compiler handles it perfectly. However, there are rare cases—such as releasing a database lock or closing a file handle early to prevent resource contention—where you want that cleanup to happen before the end of the block.

Using std::mem::drop

You might be tempted to call my_variable.drop() directly, but Rust prevents this. If you were allowed to call drop manually on a variable, the compiler would still try to call it again when the scope ends, leading to a "double free" error and a crash.

Instead, we use the std::mem::drop function. This utility takes ownership of an object and immediately lets it go out of scope, forcing its Drop implementation to run right then and there.

struct Logger;

impl Drop for Logger {
    fn drop(&mut self) {
        println!("Cleaning up the logger...");
    }
}

fn main() {
    let log = Logger;
    println!("Logger is active.");

    // We want to release the resource here, before the end of main
    drop(log);

    println!("Logger was dropped early.");
}

When you run this code, "Cleaning up the logger..." appears before "Logger was dropped early."

Why not just use curly braces?

You could wrap code in a block {} to force a variable out of scope, but drop() is often more readable and idiomatic when you only need to release one specific resource to satisfy a lock or clear a heavy memory structure. It signals to other developers that you are intentionally terminating the lifecycle of an object for a specific purpose, rather than just organizing your code blocks.

Key Takeaway: Use std::mem::drop when you need to explicitly release a resource before its scope ends, as direct calls to the drop method are prohibited by the compiler to prevent double-free errors.