Rust Scope
Scope is the region of code where a variable is valid. It’s a simple idea, but understanding it makes a lot of Rust’s other rules (especially ownership) click into place.
Scope is defined by curly braces
Section titled “Scope is defined by curly braces”A variable exists from the point it’s declared until the closing } of the block it’s in:
fn main() { let x = 5; // x comes into scope here
{ let y = 10; // y comes into scope here println!("x = {x}, y = {y}"); // both are valid } // y goes out of scope here
println!("x = {x}"); // println!("{y}"); // ❌ error: y is no longer in scope}y only exists inside the inner { } block. Once that block ends, y is gone — trying to use it afterward is a compile error, not a runtime surprise.
Function bodies are a scope too
Section titled “Function bodies are a scope too”The parameters and any variables you create inside a function only exist for the duration of that function call:
fn calculate() -> i32 { let result = 5 * 2; // result only exists inside calculate result}
fn main() { let value = calculate(); println!("{value}"); // println!("{result}"); // ❌ error: result doesn't exist out here}Why scope matters for ownership
Section titled “Why scope matters for ownership”This connects directly to something you saw on the Ownership page: a value is automatically cleaned up the moment its owner’s scope ends.
fn main() { { let text = String::from("hello"); println!("{text}"); } // text's scope ends here — Rust drops it automatically}That’s the whole mechanism behind Rust needing no garbage collector: it already knows, at compile time, exactly where every scope ends.
Shadowing and scope
Section titled “Shadowing and scope”Remember shadowing from the Variables page? Each let with the same name inside a scope creates a distinct variable — it doesn’t erase the outer one, it just takes over for the rest of that scope:
fn main() { let x = 5; { let x = x * 2; // a new x, only inside this block println!("inner x = {x}"); // 10 } println!("outer x = {x}"); // 5 — unaffected}- Scope is the region (marked by
{ }) where a variable is valid. - A variable stops existing the instant its scope’s closing
}is reached. - Function bodies are scopes too — locals inside a function disappear when it returns.
- Scope is what tells Rust exactly when to drop a value, which is why no garbage collector is needed.