Rust Reference ยท Concepts
Shadowing in Rust
Reference for shadowing in Rust: redeclaring a name with let to change its value or type, how it differs from mut, scope rules, drop timing and common patterns.
Shadowing means declaring a new variable with the same name as an existing one in the same or an enclosing scope. The new binding hides (shadows) the old one for the rest of its scope. The old value is not changed or destroyed; it simply cannot be reached by that name any more.
Because let creates a brand-new variable, a shadowing binding can have a different type and a different mutability. That makes it the idiomatic way to transform a value step by step (a string into a number, a mutable buffer into a frozen one) without inventing names like input_str and input_num.
let value = "42"; // &str let value = value.len(); // usize: a new variable, same name
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.
Syntax and rules
let name = expr; // introduces a binding let name = other_expr; // later declaration with the same name shadows the earlier one
| Situation | What happens |
|---|---|
| Same scope | The earlier binding is hidden from the point of the new let onward. |
| Inner block | The shadow lasts until the block ends, then the outer binding is visible again. |
let x = x + 1; |
The right-hand side still refers to the old x, because the new one does not exist until the statement completes. |
| Patterns | let (a, b) = ..., match arms, if let and function parameters can all shadow earlier names. |
Closures and move |
A closure sees the binding that was in scope where it was written. |
Usage notes
- Shadowing versus
mut:mutkeeps one variable and changes its value, always with the same type. Shadowing creates a new variable each time. Usemutfor state that really changes (counters, accumulators) and shadowing for one-way transformations. - Old values live on. A shadowed
Stringor guard is dropped at the end of the scope, not at the shadowinglet. If a lock or file must be released early, use a block or calldrop(old)before shadowing. This matters forDroptypes and mutex guards. - References keep the old value alive:
let a = vec![1]; let r = &a; let a = 5;is fine;rstill points at the firsta. - Closures and function parameters: a parameter can be shadowed in the body (
fn f(x: i32) { let x = x as f64; }), a common idiom for type conversion. - Readability risk: shadowing a name with an unrelated value in a long function confuses readers. Clippy has the opt-in lints
shadow_reuse,shadow_sameandshadow_unrelatedfor teams that dislike it. Seecargo clippy. - Constants cannot be shadowed by
let. Inlet MAX = 3;, aconst MAXin scope is treated as a pattern to match against, which is a compile error, not a new variable. The same applies to unit structs and enum variants in scope. - Not available for fields:
self.valueis not a variable, so there is nothing to shadow. - Macros are hygienic: a
letinside amacro_rules!expansion does not shadow the caller's variables of the same name.
Related
let,mut,Drop, Ownership rules, Patterns- Tutorial: Variables, Syntax basics