Course contentsShow
← Rust
Lesson 202 of 1,9103. Borrowing and ReferencesFree lesson

Scope-Based Resource Management

Predict when memory is freed based on the closing brace of a lexical block.

In this lesson, you will learn how Rust automatically cleans up memory the exact moment a variable's lexical scope ends.

The Life and Death of a Variable

In many programming languages, you have to manually track when to free memory or rely on a "garbage collector" that pauses your program to clean up. Rust does neither. Instead, it uses Scope-Based Resource Management.

In Rust, a "scope" is defined by a pair of curly braces {}. When you create a variable inside a block, Rust considers that variable "owned" by that block. The moment your code hits the closing brace }, the variable is immediately dropped, and the memory it occupied is freed.

Visualizing the Exit

Think of the closing brace as a deadline. As soon as the computer reaches }, the compiler guarantees that the resource is cleaned up. Consider this example:

fn main() {
    {
        let name = String::from("Rustacean");
        // 'name' is alive and usable here.
    } // <-- The closing brace: 'name' is dropped here!

    // println!("{}", name); // This would cause a compile error.
}

In the code above, the String is stored on the heap. When the program reaches the first closing brace, Rust automatically triggers the "drop" logic for name. This happens deterministically—it isn't waiting for a background process to notice the variable is unused. It happens instantly, exactly when the block ends.

This system is powerful because it prevents memory leaks without the performance cost of garbage collection. You don't have to remember to "free" anything; you simply organize your code into blocks, and Rust handles the rest by ensuring that no data outlives its welcome. If you try to use a variable after its closing brace, the compiler will stop you, ensuring you never accidentally reference memory that has already been cleared.

Key Takeaway: In Rust, a variable's life is strictly bound to the lexical scope of the block it was created in; memory is automatically and immediately freed the moment execution passes the closing brace of that block.