TExcelTAD
Home › Rust › Rust Scope

Rust Scope

The scope of a variable is the region of code where that variable exists and can be used. In Rust, scope is defined by curly braces { }: a variable lives from the line where it is declared until the end of the block that contains it.

Understanding scope is the first step towards understanding Rust's ownership system, because when a variable goes out of scope Rust automatically cleans up whatever it owns.

Block scope

Any pair of curly braces creates a new block — a function body, an if branch, a loop body, or even a bare { } that you write just to group code.

rust · try it yourself
fn main() {
    let outer = "I live in main";

    {
        let inner = "I live in the inner block";
        println!("{}", outer); // outer is visible here
        println!("{}", inner);
    } // inner is dropped here

    println!("{}", outer);
    // println!("{}", inner); // error: inner is not in scope
}
I live in main
I live in the inner block
I live in main

Inner blocks can see variables from the blocks around them, but outer code cannot see variables declared inside an inner block. If you uncomment the last line, the compiler stops with:

text
error[E0425]: cannot find value `inner` in this scope

Function scope

Each function has its own scope. A function cannot see local variables from main or from any other function — it only sees its own parameters and locals.

rust
fn show() {
    println!("{}", secret); // error: `secret` is not defined here
}

fn main() {
    let secret = 42;
    show();
}

If a function needs a value, pass it in as a parameter. This keeps functions independent and easy to reason about.

Shadowing

Rust allows you to declare a new variable with the same name as an existing one. The new variable shadows the old one: from that point on, the name refers to the new value. When the inner scope ends, the old variable becomes visible again.

rust · try it yourself
fn main() {
    let level = 1;
    println!("Start: level = {}", level);

    {
        let level = level + 10; // shadows the outer level
        println!("Inside block: level = {}", level);
    }

    println!("After block: level = {}", level);

    let level = "max"; // shadow again, even with a different type
    println!("Finally: level = {}", level);
}
Start: level = 1
Inside block: level = 11
After block: level = 1
Finally: level = max

Shadowing is different from mutation:

let mut x + x = ... let x = ... again (shadowing)
Creates a new variable? no yes
Can change the type? no yes
Original visible again after an inner block? — yes

A common use of shadowing is transforming a value step by step without inventing new names like input2 and input3.

Blocks are expressions

A block evaluates to its last expression, so you can use a block to compute a value in a small private scope. Temporary variables used for the calculation disappear afterwards.

rust · try it yourself
fn main() {
    let price = 80.0;

    let final_price = {
        let discount = 0.25;
        let tax = 0.10;
        let discounted = price * (1.0 - discount);
        discounted * (1.0 + tax)
    };

    println!("Final price: {:.2}", final_price);
    // discount, tax and discounted no longer exist here
}
Final price: 66.00

Scope and cleanup

When a variable goes out of scope, Rust calls its drop logic automatically. For simple numbers that means nothing visible, but for a String or a Vec it means their heap memory is freed. You can watch this happen by implementing the Drop trait on your own type:

rust · try it yourself
struct Noisy {
    name: &'static str,
}

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

fn main() {
    let _a = Noisy { name: "A" };
    {
        let _b = Noisy { name: "B" };
        println!("End of inner block");
    }
    println!("End of main");
}
End of inner block
Dropping B
End of main
Dropping A

B is dropped as soon as its block ends, while A lives until the end of main. There is no garbage collector and no manual free — the end of a scope is the cleanup point. Keep this in mind for the Ownership chapter.

Test yourself

Where does a variable declared inside { } stop existing?

  1. At the end of the program
  2. At the closing } of its block
  3. When it is printed
  4. When the next variable is declared

What does this print? let x = 5; { let x = x * 2; } println!("{}", x);

  1. 10
  2. 5
  3. 0
  4. It does not compile

Which statement about shadowing is true?

  1. It requires let mut
  2. It can change a variable's type
  3. It modifies the original variable
  4. It is only allowed in functions