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:
immutable.rs
// Expect: E0384fn main() { let n = 7; // n = 8; println!("{n}");}Uncomment // n = 8;, and the compiler rejects the code with a direct fix at the bottom of the diagnostic:
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 xguarantees thatxis neither reassigned nor mutated in place anywhere below, saving you from tracking state changes across the rest of the scope; seeinglet mut xsignals explicitly that updates follow. - The compiler warns on redundant
mut: if you declarelet mut n = 7;and never mutaten, the code compiles, yetrustcemits anunused_mutwarning (warning: variable does not need to be mutable) prompting you to remove the extramut.
Note also that while let mut permits updating the value, it never permits changing the variable’s type:
type-mismatch.rs
// Expect: E0308fn main() { let mut n: i32 = 7; println!("{n}"); n = 8; // n = String::from("hello"); println!("{n}");}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:
mutate-content.rs
// Expect: E0596fn main() { let s = String::from("hello"); // s.push_str("!"); println!("{s}");}Uncommenting // s.push_str("!"); produces a different compiler error:
error[E0596]: cannot borrow `s` as mutable, as it is not declared as mutableCalling 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?
replace.rs
fn main() { let mut target = String::from("old"); let source = String::from("new"); println!("{target} {source}"); target = source; println!("{target}");}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
}ofmaincannot work either, because by thentarget’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.
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:
reinitialize.rs
// Expect: E0382fn main() { let mut s = String::from("hello"); let t = s; // println!("{s}"); s = String::from("world"); println!("{s} {t}");}Running the default source prints world hello. Trace these three steps across the stack frame and the compile-time state table:
let mut s = String::from("hello");: reserves a 24-byte slot in the stack frame and recordssin the state table as holding an active value (responsible for dropping"hello").let t = s;: copies the control header bitwise intot, transfers cleanup responsibility for"hello"totin the state table, and updatessto moved-from (uncommenting// println!("{s}");right after triggersE0382)—whiles’s 24-byte slot on the stack frame stays right where it is.s = String::from("world");: consulting the state table, the compiler sees thatsis currently moved-from, emits no instruction to drop an old value, writes"world"’s control header directly intos’s existing stack slot, and restoressto holding an active value in the state table.
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.
3. Uninitialized: deferred initialization
Section titled “3. Uninitialized: deferred initialization”Splitting variable declaration and first assignment across two lines works for any type:
Source:delayed-init.rs
// Expect: E0381fn main() { let n: i32; // println!("{n}"); n = 7; println!("{n}");}Running the default code prints 7; uncommenting // println!("{n}"); to read n before assigning a value triggers an uninitialized-variable error:
error[E0381]: used binding `n` is possibly-uninitializedNotice 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 |
Hands-on check
Section titled “Hands-on check”In replace.rs, change target = source; to target = String::from("third");, keeping every other line unchanged. Trace two questions before running the code:
- After this edit, can
sourcebe printed on the last line? - 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.