2.3 Shadowing and scope: why same-named variables can coexist
The previous section established two constraints: reassigning an initialized variable directly (n = n + 1;) requires mut at declaration (otherwise E0384) and cannot change the variable’s type (otherwise E0308).
Yet the program below uses the name n three times without writing mut once—computing n + 1 and then binding n to a String—and compiles and runs without error:
shadow.rs
fn main() { let n = 7; let n = n + 1; println!("{n}"); let n = String::from("eight"); println!("{n}");}The program prints 8 and then eight. Why does prefixing let lift both constraints on the name n? And if the hidden variable owns heap memory, when is that memory dropped?
Reassignment vs. shadowing
Section titled “Reassignment vs. shadowing”The difference comes down to the underlying stack action: every let creates a brand-new variable in the stack frame.
Step through shadow.rs line by line, watching the evaluation order of let—evaluate the right-hand side of = first, then establish the new binding on the left:
let n = 7;: creates the first variable on the stack (typei32, value7) and binds the namento it.let n = n + 1;: evaluatesn + 1on the right first—because the new binding is not yet in effect,non the right still reads7from the first variable, producing8; the left-handletthen creates a second variable on the stack (storing8) and rebinds the namento that second variable.let n = String::from("eight");: the left-handletcreates a third variable on the stack whose type is determined independently asString—the earlier 4-byte integer slot never changed its type at runtime.
Creating a new variable with the same name via a fresh let so subsequent uses of that name resolve to the new binding is called shadowing. Recalling the keyword choice noted in Declarations and bindings, let makes far better sense here than var or val: because var (variable) and val (value) are nouns, writing var n or val n twice in the same scope looks like redefining the exact same item, whereas repeating let n = ... reads directly as “from this point onward, let n refer to this new value.”
Contrasting reassignment and shadowing side by side:
| Dimension | Reassignment (n = n + 1;) |
Shadowing (let n = n + 1;) |
|---|---|---|
| Variable operated on | The same existing variable | Creates a brand-new variable, rebinding subsequent uses of the name |
Original variable needs mut? |
Yes (otherwise E0384) |
No (the original variable is untouched) |
| Can the type change? | No, new value must match the original type | Yes, the new variable’s type is determined independently |
Shadowing inside a block scope
Section titled “Shadowing inside a block scope”A scope defines the region of source code where a variable can be accessed through its bound name. Placing a new let n inside an inner {} block confines shadowing to that block:
nested-shadow.rs
fn main() { let n = 7; { let n = n + 1; println!("{n}"); } println!("{n}");}The program prints 8 followed by 7. Inside the inner {}, the name n resolves to the newly created inner variable (8), temporarily shadowing the outer n. Once execution exits the inner }, the inner variable leaves scope and shadowing ends, so printing n in the outer scope reads the untouched outer variable (7).
When is a shadowed value dropped?
Section titled “When is a shadowed value dropped?”In the previous section, reassigning target = source; dropped the old value right on the = line. What if, within the same scope, you write let s = String::from("hello"); and immediately shadow it with let s = 7;? Later lines can no longer reach the old string through the name s—is the "hello" heap buffer dropped on the let s = 7; line as well?
We can test that directly with a reference experiment: borrow the address of the first s with let r = &s; before shadowing it, execute let s = 7;, and then read through r. If the old String were dropped at the shadowing line, r would immediately dangle and fail the borrow checker:
shadow-reference.rs
fn main() { let s = String::from("hello"); let r = &s; let s = 7; println!("{r} {s}");}The program compiles cleanly and prints hello 7.
That result confirms what shadowing actually does on the stack and heap:
- Shadowing neither invalidates the old variable nor drops its value on the spot.
- After
let s = 7;runs, two distinct variables coexist in the current stack frame: the old variable (String) still holds the three-word control header for"hello"in its stack slot, while the new variable (i32) occupies a separate 4-byte stack slot. let s = 7;only redirects subsequent occurrences of the namesin source code to the new variable. The referencercreated beforehand still points to the old variable’s stack address, and its valid span (up to theprintln!line) sits completely inside the old variable’s live span—satisfying the span rule from Dangling references. The"hello"heap buffer managed by the old variable stays alive untilmain’s closing}drops it automatically.
Shadowing combined with a move: let s = s;
Section titled “Shadowing combined with a move: let s = s;”What happens when the right-hand side of a shadowing statement reads the shadowed variable itself?
Source:shadow-move.rs
fn main() { let s = String::from("hello"); let s = s; println!("{s}");}On let s = s;, shadowing and a move happen together: the right-hand side evaluates first by reading the old variable s, and because String does not implement Copy, its control header and cleanup responsibility move into the newly created variable s on the left. Here the old variable does become invalid in the compile-time state table—not because of the same-named let on the left, but because the right-hand side moved its value out. At the closing } of main, only the new variable that took over responsibility drops "hello" once.
Chapter summary and comprehensive review
Section titled “Chapter summary and comprehensive review”Bringing all three sections together, analyzing any line involving let and = comes down to checking three syntax forms against their underlying actions:
| Syntax form | Underlying action | Effect on old variable and heap memory |
|---|---|---|
Initial binding (let b = a;) |
Creates a new variable and takes an initial value | Copies bitwise if Copy; moves if not Copy (invalidating source and transferring duty); borrows with & (leaving duty untouched) |
Reassignment (x = new_val;) |
Updates the same existing variable (requires let mut, keeps same type) |
If x currently holds an active move value, drops the old value at the = line first before taking the new one; if moved-from or uninitialized, writes the new value directly |
Shadowing (another let x = ...;) |
Creates a same-named new variable and rebinds later uses of the name (no mut needed, can change type) |
Old variable is not dropped immediately; coexists with the new variable on the stack frame and drops at its enclosing } (unless the right-hand side moved its value out) |
Code-tracing review
Section titled “Code-tracing review”Without running the program below first, trace the compile-time state table and each heap allocation line by line using the table above:
Source:review.rs
fn main() { let mut s = String::from("first"); let t = s; s = String::from("second"); println!("{s}"); { let r = &t; let s = 7; println!("{s} {r}"); } s = t; let s = s; println!("{s}");}Answer three questions:
- What do the three
println!calls output in order? - Is
"second"on the heap dropped at the inner block’s closing}, or dropped on the spot whens = t;executes afterward? - When
mainreaches its closing}, which variable drops"first"?
Check the line-by-line trace
- Printed output:
second,7 first, andfirstin order. - First four outer statements (move and refilling a vacated slot):
let mut s = String::from("first");: outersholds"first".let t = s;: moves"first"intot, transferring cleanup responsibility totand marking outersas moved-from.s = String::from("second");: writes a fresh value into the moved-from outers(triggering no drop), restoring outersto valid as the owner of"second". The firstprintln!outputssecond.
- Inner
{}block (borrowing and block-scoped shadowing):let r = &t;: borrowst(pointing to"first").let s = 7;: creates a new integer variablesinside the inner block, temporarily shadowing the outer string variables. The secondprintln!outputs7 first.- Inner
}closes: only the inner integersand referencerleave scope; outersstill belongs to the outer scope, so"second"is not dropped at the inner}.
- Final three outer statements (overwrite drop and same-name move):
s = t;: outerscurrently holds an active"second", so reassigning it drops"second"on the spot on this line while moving"first"out oftinto outers(invalidatingt).let s = s;: creates a new variablesand moves"first"from the old outersinto that news. At the closing}ofmain, that final variablesdrops"first".
Next, verify one targeted edit in review.rs: inside the inner block, replace let s = 7; with s = String::from("third"); (omitting let). Without let, the inner statement stops creating a new variable and reassigns the outer mutable variable s directly—dropping "second" on the spot inside the inner block and replacing it with "third" (changing the second printout to third first). When outer s = t; runs afterward, the buffer replaced and dropped on the spot becomes "third".
Hands-on coding: mutate during setup, then lock down as read-only
Section titled “Hands-on coding: mutate during setup, then lock down as read-only”Open the Playground on any example above (or a local src/main.rs) and write a short fn main() from scratch completing three steps:
- Create a heap-backed string variable
docholding"draft"and append a version suffix by calling.push_str(" v1"). - Once setup is complete—without allocating extra heap memory (no
.clone())—keep the variable namedocwhile locking it down as an immutable binding (so an accidentaldoc.push_str(" v2")afterward would be rejected withE0596). - Create a read-only borrow
previewpointing to the lockeddoc, and print bothdocandpreview.
Check the reference implementation
fn main() { let mut doc = String::from("draft"); doc.push_str(" v1");
let doc = doc; // doc.push_str(" v2"); // Uncommenting triggers E0596 because the new binding is immutable let preview = &doc; println!("{doc} | {preview}");}let doc = doc; creates a new immutable variable of the same name at compile time and moves the three-word control header along with cleanup responsibility from the old doc into the new one, keeping a single heap buffer throughout. preview then borrows the stack address of the new doc, allowing both to print before the new doc drops the heap buffer at }.
Next step: into types
Section titled “Next step: into types”Across the two chapters of this part, we derived ownership, borrowing, and lifetimes from stack and heap mechanics, and verified how the compile-time state table governs variable declarations, reassignment, and shadowing in real Rust code.
Looking back over the code in this chapter, writing the exact same statement let b = a; triggered copy, move, or borrowing depending solely on whether the right-hand side had type i32, String, or &String; adding mut unlocked mutation while keeping the variable locked to the type fixed at declaration. In a language with neither class definitions nor runtime object headers, what information does a “type” actually carry, and how do types combine to build rich data structures? The next part enters Types to unpack that foundation.