Skip to content

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.

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
}
▶ Try it Yourself

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.

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
}
▶ Try it Yourself

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
}
▶ Try it Yourself

That’s the whole mechanism behind Rust needing no garbage collector: it already knows, at compile time, exactly where every scope ends.

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
}
▶ Try it Yourself
  • 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.

Quick check

1. Why doesn't Rust need a garbage collector, according to this page?

2. What happens when you shadow a variable with let x = x * 2; inside an inner block?

Score: 0 / 2