Skip to content

2.2 Mutability and reassignment: where the old value goes

Every = in the previous section carried let on the left to establish an initial binding when declaring a new variable. Once a variable has been declared, writing x = ... later without let updates that existing variable and raises two questions: what an immutable binding restricts by default, and where the previous value goes when a new value takes its place.

Immutable by default and the two permissions of let mut

Section titled “Immutable by default and the two permissions of let mut”

If you come from JavaScript or TypeScript, watch the inverted keyword convention: in JS/TS, let declares a mutable variable while const marks an immutable one; Rust flips that default—a plain let creates an immutable binding, and permitting mutation requires writing let mut explicitly.

For an ordinary owning variable, an immutable binding restricts two distinct mutation permissions at once.

1. First permission: reassignment (x = ...)

Section titled “1. First permission: reassignment (x = ...)”

In the program below, n is initialized to 7, and the commented line attempts to replace it with 8:

Source: immutable.rs
// Expect: E0384
fn main() {
let n = 7;
// n = 8;
println!("{n}");
}
Run in the Rust Playground

Uncomment // n = 8;, and the compiler rejects the code with a direct fix at the bottom of the diagnostic:

Compiler output (after uncommenting the line in immutable.rs)
error[E0384]: cannot assign twice to immutable variable `n`
--> src/bin/immutable.rs:4:5
|
3 | let n = 7;
| - first assignment to `n`
4 | n = 8;
| ^^^^^ cannot assign twice to immutable variable
|
help: consider making this binding mutable
|
3 | let mut n = 7;
| +++

error[E0384] blocks reassignment (including compound assignments such as n += 1;). Adding mut at the declaration as suggested in help (let mut n = 7;) allows writing a new value into n.

At this point, newcomers often wonder: if adding mut silences the error, why not write let mut on every variable by default? Two engineering and compiler facts push against that habit:

  • Narrowing where state can change: while reading a function, seeing let x guarantees that x is neither reassigned nor mutated in place anywhere below, saving you from tracking state changes across the rest of the scope; seeing let mut x signals explicitly that updates follow.
  • The compiler warns on redundant mut: if you declare let mut n = 7; and never mutate n, the code compiles, yet rustc emits an unused_mut warning (warning: variable does not need to be mutable) prompting you to remove the extra mut.

Note also that while let mut permits updating the value, it never permits changing the variable’s type:

Source: type-mismatch.rs
// Expect: E0308
fn main() {
let mut n: i32 = 7;
println!("{n}");
n = 8;
// n = String::from("hello");
println!("{n}");
}
Run in the Rust Playground

Uncommenting // n = String::from("hello"); triggers a type mismatch (error[E0308]: mismatched types, expected i32, found String). At declaration, n was fixed as a 4-byte i32 on the stack; mut lets you write another i32 into that slot, not convert it into a 24-byte String control header carrying heap cleanup responsibility.

2. Second permission: mutating internal data

Section titled “2. Second permission: mutating internal data”

Now check the second permission. Declare an immutable binding let s = String::from("hello");, avoid any s = ... reassignment, and call s.push_str("!") to append text to its heap buffer:

Source: mutate-content.rs
// Expect: E0596
fn main() {
let s = String::from("hello");
// s.push_str("!");
println!("{s}");
}
Run in the Rust Playground

Uncommenting // s.push_str("!"); produces a different compiler error:

Compiler output (after uncommenting the line in mutate-content.rs)
error[E0596]: cannot borrow `s` as mutable, as it is not declared as mutable

Calling s.push_str("!") updates len inside the stack control header and modifies bytes in the heap buffer. On an ordinary owning variable without let mut, the compiler blocks both reassigning the variable (E0384) and obtaining mutable access through it to modify internal data (E0596). Writing let mut s = String::from("hello"); unlocks both permissions together (how the compiler recognizes from push_str’s method signature alone that the call requires a mutable borrow is unpacked later in Method receivers and autoderef).

Like move invalidation, mutability lives solely in the compiler’s compile-time state table, adding zero tag bits in runtime memory. Whether you write let n = 7; or let mut n = 7;, the runtime stack frame holds the exact same 4 integer bytes; the compiler verifies permissions against its state table during compilation and then emits ordinary machine instructions.

Three states of reassignment: where the old value goes

Section titled “Three states of reassignment: where the old value goes”

With the permission rules settled, return to x = new_val; itself: when a new value is written into x, what happens to the value x held previously?

For Copy types such as i32, reassignment overwrites the 4 bytes on the stack with no heap cleanup involved. For move types such as String that carry exclusive cleanup responsibility, the compiler consults its state table right before the = line—checking whether the variable currently holds an active value, has already been moved from, or has not yet been initialized—and handles each state differently.

1. Holding an active value: drop the old value on the spot

Section titled “1. Holding an active value: drop the old value on the spot”

The baseline rule from the previous chapter drops heap allocations when their owner leaves scope (}). What if, well before reaching }, a variable target holding an active string executes target = source; to take on a new value—when is its original heap buffer freed?

Source: replace.rs
fn main() {
let mut target = String::from("old");
let source = String::from("new");
println!("{target} {source}");
target = source;
println!("{target}");
}
Run in the Rust Playground

Running the program prints old new followed by new.

Before target = source; runs, target owns cleanup responsibility for "old" and source owns cleanup responsibility for "new". As "new"’s control header is about to overwrite target’s stack slot:

  • Overwriting target’s control header without freeing "old" first would lose the last pointer to "old" on the stack, leaking memory immediately.
  • Waiting until the closing } of main cannot work either, because by then target’s slot holds "new".

Consequently, when reassigning a move-type variable that currently holds an active value, the compiler drops the variable’s old value right at the = line before moving the new control header into its slot.

At target = source;: the "old" heap buffer previously owned by target is dropped on the spot, and source's control header moves into target (leaving source invalid).
Stack and heap layout at target = source;On the stack frame, variable target (String) holds an active three-word control header (ptr, len 3, cap 3) whose ptr arrow points to the "new" character buffer on the heap. Below it, variable source (String) is marked invalid with its three machine words shown in dashed outlines and no arrow. On the heap, the top buffer "old" is shown in dashed outlines as dropped in place, while the bottom buffer "new" is active.stack frametargetStringptrlen · 3cap · 3sourceStringinvalidptrlen · 3cap · 3heapold buffer (dropped in place)oldcharacter buffernew

Tracking both heap buffers in execution order:

Point in execution "old" heap buffer "new" heap buffer
Before target = source; Held by target, which owns cleanup duty Held by source, which owns cleanup duty
At target = source; Dropped on the spot before overwrite Control header moves into target (source invalidated); now target’s duty
At closing } of main Already dropped at the assignment line Dropped as target leaves scope

This completes the drop timing rule from the previous chapter: an owner’s cleanup responsibility fires not only on leaving scope (}), but also right on the line where an active value is overwritten by reassignment.

2. Value moved out: write directly into the vacated slot

Section titled “2. Value moved out: write directly into the vacated slot”

Now consider what happens when a move-type variable s initially holds a value, moves that value to another variable, and is then reassigned:

Source: reinitialize.rs
// Expect: E0382
fn main() {
let mut s = String::from("hello");
let t = s;
// println!("{s}");
s = String::from("world");
println!("{s} {t}");
}
Run in the Rust Playground

Running the default source prints world hello. Trace these three steps across the stack frame and the compile-time state table:

  1. let mut s = String::from("hello");: reserves a 24-byte slot in the stack frame and records s in the state table as holding an active value (responsible for dropping "hello").
  2. let t = s;: copies the control header bitwise into t, transfers cleanup responsibility for "hello" to t in the state table, and updates s to moved-from (uncommenting // println!("{s}"); right after triggers E0382)—while s’s 24-byte slot on the stack frame stays right where it is.
  3. s = String::from("world");: consulting the state table, the compiler sees that s is currently moved-from, emits no instruction to drop an old value, writes "world"’s control header directly into s’s existing stack slot, and restores s to holding an active value in the state table.
After let t = s; and s = String::from("world");: "hello" was already moved to t (not dropped), while the vacated s takes ownership of "world" and becomes valid again, leaving both heap buffers alive.
Stack and heap layout after let t = s; and s = String::from("world");On the stack frame, top variable s (String, marked valid again) holds an active three-word control header (ptr, len 5, cap 5) whose ptr arrow points to the five-character buffer "world" on the heap. Below it, variable t (String) also holds an active three-word control header (ptr, len 5, cap 5) whose ptr arrow points to the original five-character buffer "hello" on the heap. Both variables and both heap buffers remain alive simultaneously.stack framesStringvalid againptrlen · 5cap · 5tStringptrlen · 5cap · 5heapbuffer (owned by s)worldoriginal buffer (moved to t, still alive)hello

This confirms in runnable code the hardware reality uncovered in Copy and move: moving out of s never destroys the variable s itself—it temporarily marks s as moved-from in the compile-time state table. The compiler tracks variable liveness line by line along control flow: reading s after the move and before refilling is rejected, whereas writing a fresh value into s’s stack slot restores s to valid. Both "world" and "hello" then remain alive on the heap simultaneously until the closing } of main, where s and t drop their respective buffers.

Splitting variable declaration and first assignment across two lines works for any type:

Source: delayed-init.rs
// Expect: E0381
fn main() {
let n: i32;
// println!("{n}");
n = 7;
println!("{n}");
}
Run in the Rust Playground

Running the default code prints 7; uncommenting // println!("{n}"); to read n before assigning a value triggers an uninitialized-variable error:

Compiler output (after uncommenting the line in delayed-init.rs)
error[E0381]: used binding `n` is possibly-uninitialized

Notice that let n: i32; omits mut, yet n = 7; below still compiles. let n: i32; performs only a declaration, recording n in the state table as uninitialized; the subsequent n = 7; is first-time initialization rather than reassignment over an existing value, so there is neither an old value to drop nor any requirement for let mut.

Comparing and checking the three assignment states

Section titled “Comparing and checking the three assignment states”

Summarizing all three forms of x = ... (without let) against the compile-time state table:

Static state of x before = Typical pattern Action at x = new_val; Requires let mut?
Holding an active value (initialized and not moved out) let mut target = ...;
target = source;
For move types, drops the old value at the = line first, then takes the new value Yes
Moved-from (initialized earlier, moved to another variable) let mut s = ...;
let t = s;
s = new_s;
Old value now belongs to t, so nothing is dropped here; writes new value and restores s to valid Yes
Uninitialized (declared only, no value stored yet) let n: i32;
n = 7;
First-time initialization with no old value to drop; becomes valid afterward (reading earlier triggers E0381) No

In replace.rs, change target = source; to target = String::from("third");, keeping every other line unchanged. Trace two questions before running the code:

  1. After this edit, can source be printed on the last line?
  2. On which line is each of the three heap buffers—"old", "new", and "third"—dropped?

Verification: source is never moved, so it stays valid and prints cleanly. Among the three heap buffers, "old" is replaced and dropped on the spot at target = String::from("third");, while "new" and "third" remain owned by source and target and are dropped at the closing } of main.

Every x = ... in this section omitted let, operating on the exact same variable slot throughout. Rust code also makes frequent use of another pattern: writing let a second time with the same name (such as let s = String::from("hello"); followed by let s = 7;). Is the old string hidden behind that same-named binding dropped on the spot too? The next section unpacks shadowing and scope.