bhylu.com

Advertisements

Rust Scope and Shadowing

Understand which binding an expression uses.

How it works

A binding’s scope determines where its name is available. A nested block can shadow an outer binding without changing the original value. Values are dropped when their owning scope ends according to Rust’s rules. Scope alone does not make a reference valid forever; borrowing and lifetime checks also constrain whether a value can outlive what it points to.

Run the code

Reviewed with Rust 1.97.0, edition 2024, using the standard library only. Save the complete download as lesson-name.rs in a separate learning folder, compile with rustc --edition=2024 lesson-name.rs and run the resulting program (lesson-name.exe on Windows). Use the actual lesson filename. The final project includes complete Cargo package files; run cargo test --offline and cargo run --offline from that separate package folder. There is no Rust browser runner; PHP, Apache and MySQL are not needed.

This complete example was executed in the stated local review environment.

Download complete source

Example

scope.rs

fn main() {
    let label = "north";
    {
        let label = label.len();
        assert_eq!(label, 5);
    }
    assert_eq!(label, "north");
    println!("Inner length 5; outer label north");
}

Expected result

Inner length 5; outer label north

The inner name has an integer type while the outer remains a string slice. This is a new binding, not mutation of the original string. Shadowing can clarify a validated conversion, but too many unrelated meanings for one name make an interface harder to review.

Primary technical reference: Rust documentation.