Sub topic 6
Fixing immutable assignment errors
This chapter covers the errors rustc reports when code changes a value that was not declared as changeable. You should already be comfortable with let bindings, function parameters, structs, and references, and with the basic idea of & and &mut. The chapter also assumes you can read the parts of a diagnostic (code, message, labels, help) from the first chapter of this tutorial.
Why Rust rejects these assignments
In Rust, a binding is immutable by default. A binding is the name you introduce with let, a function parameter, or a pattern. You can read through an immutable binding, but you cannot assign to it again or change the value it owns.
The compiler reports this in several forms. The form depends on what you tried to change:
| Code | What you tried | Typical message |
|---|---|---|
| E0384 | Assign to a variable or parameter a second time | cannot assign twice to immutable variable |
| E0594 | Assign to a field, or through a `&` reference | cannot assign to `c.count`, as `c` is not declared as mutable |
| E0596 | Take a `&mut` borrow, often by calling a `&mut self` method | cannot borrow `list` as mutable, as it is not declared as mutable |
All three come from the same rule. Mutation needs either a mut binding that owns the value, or a &mut reference to it. The fix is to give the code one of these, or to restructure so that no mutation is needed.
E0384: assigning to an immutable variable
This is the simplest case. The program below does not compile.
fn main() {
let total = 0;
total += 1;
println!("{total}");
}The diagnostic looks like this. The exact wording varies slightly between compiler versions.
error[E0384]: cannot assign twice to immutable variable `total`
--> src/main.rs:3:5
|
2 | let total = 0;
| ----- first assignment to `total`
3 | total += 1;
| ^^^^^^^^^^ cannot assign twice to immutable variable
|
help: consider making this binding mutable
|
2 | let mut total = 0;
| +++The primary span (the ^^^^ line) marks the second assignment. The secondary label (the ----- line) marks the first one. The help text shows the fix, with +++ marking the characters to add. If the variable really is meant to change, add mut:
fn main() {
let mut total = 0;
total += 1;
println!("{total}");
}Deferred initialization is not an error
Rust lets you declare a binding without a value and assign it once later. The compiler checks that every path assigns exactly once before the value is read.
fn main() {
let label;
let score = 72;
if score >= 60 {
label = "pass";
} else {
label = "fail";
}
println!("{label}");
}Each branch assigns label once, so this compiles with no mut. If you added a second label = ... after the if, you would get E0384. This pattern is often better than let mut followed by overwriting, because the binding stays immutable after it is set.
Choosing between `mut`, shadowing, and restructuring
Adding mut is not always the best fix. Consider three options:
- Add
mutwhen the value changes repeatedly, as with accumulators and loop counters. - Shadow the name when you are computing a new value from an old one in a few steps.
- Restructure into an expression when the value is assigned once, conditionally.
Shadowing means declaring a new binding with the same name. It creates a separate variable and does not mutate the old one. Shadowing can also change the type.
fn main() {
let input = "42";
let input = input.trim();
let input: i32 = input.parse().unwrap();
let input = input + 1;
println!("{input}");
}Every let here makes a new immutable binding. Using if as an expression gives the same single-assignment result as the deferred example above:
fn main() {
let score = 72;
let label = if score >= 60 { "pass" } else { "fail" };
println!("{label}");
}E0594: assigning to a field
A struct binding is mutable or immutable as a whole. You cannot make one field mutable and leave the others fixed. The code below does not compile.
struct Counter {
count: u32,
}
fn main() {
let c = Counter { count: 0 };
c.count += 1;
println!("{}", c.count);
}rustc reports error[E0594]: cannot assign to c.count, as c is not declared as mutable. The help points at the declaration of c. The fix is let mut c.
struct Counter {
count: u32,
}
fn main() {
let mut c = Counter { count: 0 };
c.count += 1;
println!("{}", c.count);
}E0384 on parameters
Function parameters are bindings too, so they are immutable unless declared with mut. The compiler words this as "cannot assign to immutable argument". The code below does not compile.
fn bump(n: i32) -> i32 {
n += 1;
n
}You have two reasonable fixes. Write mut n: i32 if you want to modify a local copy. Or return a new value and avoid mutation:
fn bump(n: i32) -> i32 {
n + 1
}
fn main() {
let x = 5;
println!("{}", bump(x));
}A mut n parameter changes only the function's own copy of n. It does not change the caller's variable. A common mistake is to add mut to the parameter, see the error disappear, and then wonder why the caller's value did not change. If the caller's value must change, take &mut i32 instead.
E0596: borrowing mutably through the wrong binding
Methods like Vec::push take &mut self. Calling one needs a mutable borrow of the receiver. Two things can block it. The binding may not be mut, or the value may only be reachable through a shared reference. The code below does not compile, and it hits both.
fn add_item(list: &Vec<i32>) {
list.push(1);
}
fn main() {
let items = Vec::new();
add_item(&items);
println!("{}", items.len());
}The first error is cannot borrow list as mutable, as it is behind a & reference. The `list in the message means the value that list points to. The help suggests changing the parameter type to &mut Vec<i32>. Once you do, the call site needs &mut items, and items needs mut`:
fn add_item(list: &mut Vec<i32>) {
list.push(1);
}
fn main() {
let mut items = Vec::new();
add_item(&mut items);
println!("{}", items.len());
}Fix these in order. Change the function signature first, then recompile, then fix the call site. Each change exposes the next requirement, and that is expected.
Mutating through loops and closures
Two situations produce these errors in code that looks reasonable.
Iterating with a shared reference
for item in &items yields &Item, which cannot be assigned through. This fails with E0594, "cannot assign to item.count, which is behind a & reference". Use iter_mut() or &mut items, which yield &mut Item:
struct Item {
count: u32,
}
fn main() {
let mut items = vec![Item { count: 1 }, Item { count: 2 }];
for item in &mut items {
item.count += 10;
}
for item in &items {
println!("{}", item.count);
}
}The vector itself must be mut, because &mut items needs a mutable binding.
Calling a closure that mutates state
A closure that changes a captured variable is an FnMut closure. Calling it requires a mutable borrow of the closure itself. So the closure binding must be mut, even though the closure never reassigns its own name. Without it, rustc reports E0596, "cannot borrow next_id as mutable, as it is not declared as mutable". The working version is:
fn main() {
let mut id = 0;
let mut next_id = || {
id += 1;
id
};
println!("{}", next_id());
println!("{}", next_id());
}Both id and next_id need mut. Forgetting the second one is a frequent surprise.
When `mut` is the wrong answer
Sometimes the compiler's mut suggestion is technically valid but poor design. Check these cases before accepting it:
- You cannot change the signature. A trait method may be fixed as
&self. Addingmutto the receiver would stop the impl from matching the trait. Interior mutability types such asCellandRefCellallow mutation through&self. They move the borrow checks to runtime, so use them only when the shared-access design is deliberate. - The mutation hides a simple computation. If you build a value with several
let mutsteps, an expression or iterator chain is often clearer and keeps the result immutable. - A shared value should not change. If many parts of the program read the same data, an immutable binding documents that guarantee. Making it
mutloosens it.
A repeatable fix routine
- Read the primary span. It shows which assignment or method call needs mutation.
- Look at the secondary label to find the declaration that lacks
mut. - Decide whether the value should change at all. Shadowing or an expression may remove the need.
- If the value is behind
&, change the type to&mutand update every call site. - Run
cargo checkafter each change. Each fix may reveal the next error in the chain.
Exercise
This function fails to compile with E0596. Name the two edits that fix it, and say which edit must come first. fn clearall(names: &Vec<String>) { names.clear(); } fn main() { let names = vec![String::from("a")]; clearall(&names); }
Show answer
First change the parameter type to &mut Vec<String>, because the method clear needs a mutable borrow and the current reference is shared. Then change main to declare let mut names and call clear_all(&mut names), because a &mut borrow can only be taken from a mut binding. The signature edit comes first. Once it is in place, the compiler points at the call site and the missing mut.
Exercise
A learner writes fn bump(mut n: i32) { n += 1; }, calls bump(x), and finds that x is unchanged. Why, and what are two ways to get the intended behavior?
Show answer
The mut makes only the parameter n mutable, and n is a copy of x. Changing the copy does not affect the caller's variable. Either return the new value (fn bump(n: i32) -> i32 { n + 1 } and x = bump(x) with let mut x) or take a mutable reference (fn bump(n: &mut i32) { *n += 1; } and call bump(&mut x)).