Skip to content

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:

Source: shadow.rs
fn main() {
let n = 7;
let n = n + 1;
println!("{n}");
let n = String::from("eight");
println!("{n}");
}
Run in the Rust Playground

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?

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:

  1. let n = 7;: creates the first variable on the stack (type i32, value 7) and binds the name n to it.
  2. let n = n + 1;: evaluates n + 1 on the right first—because the new binding is not yet in effect, n on the right still reads 7 from the first variable, producing 8; the left-hand let then creates a second variable on the stack (storing 8) and rebinds the name n to that second variable.
  3. let n = String::from("eight");: the left-hand let creates a third variable on the stack whose type is determined independently as String—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

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:

Source: nested-shadow.rs
fn main() {
let n = 7;
{
let n = n + 1;
println!("{n}");
}
println!("{n}");
}
Run in the Rust Playground

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).

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:

Source: shadow-reference.rs
fn main() {
let s = String::from("hello");
let r = &s;
let s = 7;
println!("{r} {s}");
}
Run in the Rust Playground

The program compiles cleanly and prints hello 7.

After shadowing with let s = 7;: the old s (String) and new s (i32) coexist on the stack frame; the name s now resolves to the new variable, while r still points to the old s and "hello" on the heap remains alive.
Stack and heap layout after shadowing s with let s = 7; while r borrows the old sOn the stack frame, three variables coexist: at the top, r (&String) is one machine word holding the stack address of the old s, with a solid arrow pointing down to the old s. In the middle, the old s (String, shadowed but still valid) holds an active three-word control header (ptr, len 5, cap 5) whose ptr arrow points to the active five-character buffer "hello" on the heap. At the bottom, the new s (i32, where the name s now resolves) holds 7 in an active slot. Nothing is freed.stack framer&Stringstack address of old spoints at old sold sString(shadowed, still valid)ptrlen · 5cap · 5new si32(name s resolves here)7heapcharacter buffer(still owned by old s)hello

That result confirms what shadowing actually does on the stack and heap:

  1. Shadowing neither invalidates the old variable nor drops its value on the spot.
  2. 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.
  3. let s = 7; only redirects subsequent occurrences of the name s in source code to the new variable. The reference r created beforehand still points to the old variable’s stack address, and its valid span (up to the println! 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 until main’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}");
}
Run in the Rust Playground

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.

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)

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}");
}
Run in the Rust Playground

Answer three questions:

  1. What do the three println! calls output in order?
  2. Is "second" on the heap dropped at the inner block’s closing }, or dropped on the spot when s = t; executes afterward?
  3. When main reaches its closing }, which variable drops "first"?
Check the line-by-line trace
  1. Printed output: second, 7 first, and first in order.
  2. First four outer statements (move and refilling a vacated slot):
    • let mut s = String::from("first");: outer s holds "first".
    • let t = s;: moves "first" into t, transferring cleanup responsibility to t and marking outer s as moved-from.
    • s = String::from("second");: writes a fresh value into the moved-from outer s (triggering no drop), restoring outer s to valid as the owner of "second". The first println! outputs second.
  3. Inner {} block (borrowing and block-scoped shadowing):
    • let r = &t;: borrows t (pointing to "first").
    • let s = 7;: creates a new integer variable s inside the inner block, temporarily shadowing the outer string variable s. The second println! outputs 7 first.
    • Inner } closes: only the inner integer s and reference r leave scope; outer s still belongs to the outer scope, so "second" is not dropped at the inner }.
  4. Final three outer statements (overwrite drop and same-name move):
    • s = t;: outer s currently holds an active "second", so reassigning it drops "second" on the spot on this line while moving "first" out of t into outer s (invalidating t).
    • let s = s;: creates a new variable s and moves "first" from the old outer s into that new s. At the closing } of main, that final variable s drops "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:

  1. Create a heap-backed string variable doc holding "draft" and append a version suffix by calling .push_str(" v1").
  2. Once setup is complete—without allocating extra heap memory (no .clone())—keep the variable name doc while locking it down as an immutable binding (so an accidental doc.push_str(" v2") afterward would be rejected with E0596).
  3. Create a read-only borrow preview pointing to the locked doc, and print both doc and preview.
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}");
}
Run in the Rust Playground

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 }.

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.