Rust Scope
Scope is the block of code where a variable lives. The variable is gone when the block ends.
Shadowing: a new variable with the same name
The second let does not change x. It makes a new x that hides the old one:
let x = 5;
let x = x + 1;Inside a block, the shadow rules
The inner x is a new variable. It rules inside the block, and the outer x is back the moment the block ends:
let x = 5;
{
let x = x * 2;
println!("inside: x = {x}");
}
println!("outside: x = {x}");A shadow may change the type
Text first, then a number counted from it. A shadow may switch type like this — a mut variable never may:
let spaces = " ";
let spaces = spaces.len();
println!("spaces = {spaces}");A block's own names stay inside
y is made inside the block, so it is gone after the closing brace. Using it outside fails:
{
let y = 10;
}
println!("{y}"); // error E0425: cannot find value `y` in this scopeFreeze a value by rebinding it
Sort while mut is allowed, then rebind without mut. From that line on, data is read-only — even for you.
let mut data = [3, 1, 2];
data.sort();
let data = data;
println!("{data:?}");Example
fn main() {
let word = " rust ";
let word = word.trim();
let word = word.len();
println!("letters = {}", word);
}Key points
- A variable lives from the line where it is created to the end of its { } block
- A shadowed variable may have a different type.
- A mut variable may not change type.
- Use a plain { } block on purpose to give helper names a short life.
- They end at the closing brace.
- The outer names carry on.
- Shadowing creates a brand-new variable and leaves the old one untouched underneath.
In this example, the name word is used three times, and each let creates a new variable. First, word is the text " rust ", with spaces. Then word is shadowed by its trimmed version, "rust". Then it is shadowed again by a number: the length of the text, 4. Each step stayed immutable — no mut was needed — yet the name stayed clear and meaningful.
Note
Shadowing is not the same as mut.
mut changes one variable.
Try it Yourself
Edit the code, then press Run.
Running is simulated · Rust Playground
Exercise
How is shadowing different from mut?