Sub topic 6
Fixing immutable assignment errors
This chapter assumes you can read the parts of a rustc diagnostic (code, message, span, help), run cargo check, and know what let bindings and references are. Here you will fix the errors that appear when code changes a value that Rust treats as read-only.
Bindings are immutable by default
A let binding cannot be changed after it is initialized unless you write mut. The compiler enforces this at compile time, so an assignment to a plain binding is rejected.
fn main() {
let total = 0;
total += 1;
println!("{total}");
}cargo check reports roughly this (abbreviated):
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 labels show two places. The first marks the declaration, which fixed the binding as read-only. The second marks the assignment that broke the rule. The help section gives the exact edit.
The fix: declare the binding mutable
fn main() {
let mut total = 0;
total += 1;
println!("{total}");
}Add mut only to bindings that really change. A binding that never changes should stay immutable, because readers can then trust its value everywhere.
Fix by restructuring, not only by adding mut
Sometimes mut is the wrong fix. If you assign once per branch, or compute a value in one step, an immutable binding can still work.
fn main() {
let score = 72;
let grade = if score >= 90 { "A" } else if score >= 70 { "B" } else { "C" };
println!("{grade}");
}Here grade is assigned exactly once, so no mut is needed. Rust also allows a late first assignment, such as let grade; followed by one assignment in each branch. A second assignment to the same binding is the error.
Related errors: mutable borrows
Mutating through a method or a reference has its own codes. All of them come from the same rule.
| Code | Typical message | Cause |
|---|---|---|
| E0384 | cannot assign twice to immutable variable | Reassigning a non-`mut` binding |
| E0596 | cannot borrow as mutable | Calling a `&mut self` method on a non-`mut` binding, or through a `&` reference |
| E0594 | cannot assign to field of immutable binding | Writing to a struct field through a non-`mut` binding or `&` reference |
Calling push needs a mutable borrow of the vector, so the binding must be mut:
fn main() {
let mut names = Vec::new();
names.push("Ada");
println!("{names:?}");
}Without mut on names, rustc reports E0596 and suggests the same edit.
Mutating through a reference parameter
For a function parameter, the fix is in the type, not the binding. A &Vec<i32> is a shared reference and does not allow changes.
fn add_one(list: &mut Vec<i32>) {
list.push(1);
}
fn main() {
let mut data = vec![5, 6];
add_one(&mut data);
println!("{data:?}");
}Three edits work together: &mut in the parameter type, mut on the caller's binding, and &mut at the call site. If you miss one, the compiler points at that spot.
Looking ahead
Mutability and borrowing are linked. Once a binding is mut, you can create mutable references, and the rules about having them alongside other references produce the errors in the next chapters.
Exercise
This code fails with E0596. What two changes make it compile? fn main() { let items = vec![1, 2]; items.push(3); println!("{items:?}"); }
Show answer
Declare the binding as mutable with let mut items = vec![1, 2];. That is the only change needed, because push needs a mutable borrow of items. The error is E0596, not E0384, since the code borrows mutably instead of reassigning. If items were a &Vec<i32> parameter, you would instead change its type to &mut Vec<i32>.