Sub topic 3
Opting into change with mut
What this chapter covers
This chapter assumes you have read the previous two chapters. You know how let creates a binding, and you know that bindings are immutable by default. Here you will learn what mut changes, what it leaves alone, and how to decide when a variable should be mutable.
After this chapter you should be able to:
- Declare mutable bindings, parameters, and pattern variables.
- Predict which assignments and method calls the compiler accepts or rejects.
- Explain why
mutcannot change a variable's type. - Keep mutation narrow so that it stays easy to reason about.
What mut does
Adding mut after let marks the binding as one whose value can be replaced or modified in place.
fn main() {
let mut count = 0;
println!("start: {count}");
count += 1;
println!("after +=: {count}");
count = count * 10;
println!("after reassignment: {count}");
}This prints start: 0, after +=: 1, and after reassignment: 10. Without mut, the second statement would fail with error[E0384]: cannot assign twice to immutable variable.
mut is a property of the binding, not of the value. It says "through this name, you may change the value." Rust checks this at compile time, so it adds no runtime cost. A mutable i32 has the same size and speed as an immutable one.
What mut does not do
mut allows a binding to hold a different value of the same type. It does not allow a different type. The type is fixed when the binding is created, whether you wrote it or the compiler inferred it.
fn main() {
let mut spaces = " ";
spaces = " "; // fine: still a &str
println!("{}", spaces.len());
// spaces = spaces.len(); // error[E0308]: mismatched types
// // expected `&str`, found `usize`
}If you need to change the type, use shadowing (let spaces = spaces.len();), which the previous chapter covered. Mutation and shadowing solve different problems:
| Goal | Tool |
|---|---|
| Update a value in place, same type | `let mut` and assignment |
| Transform a value, possibly changing its type | Shadowing with a new `let` |
| Make a value read-only after setup | Shadow a mutable binding with an immutable one |
Where mut can appear
The keyword shows up in several positions. They look similar but mean slightly different things.
| Form | Meaning |
|---|---|
| `let mut x = 0;` | The binding `x` can be reassigned and modified. |
| `fn f(mut n: u32)` | The parameter is a local, modifiable copy or owned value. |
| `let (mut a, b) = (1, 2);` | Only `a` is mutable. `b` is not. |
| `&mut T` | A mutable reference. It allows modification of the value it points to. |
| `let r = &mut x;` | `r` itself is immutable, but it can modify `x` through the reference. |
Mutable parameters
A parameter marked mut is a local variable of the function. Changing it does not affect the caller's variable when the argument is a plain value such as an integer.
fn countdown(mut n: u32) -> u32 {
let mut steps = 0;
while n > 0 {
n -= 1;
steps += 1;
}
steps
}
fn main() {
let start = 3;
println!("{}", countdown(start));
println!("{start}"); // still 3
}The output is 3 and then 3. The caller's start is not mutable and is not changed, because u32 is copied into the function.
Mutable patterns
Each variable in a pattern gets its own mut. This lets you destructure a tuple and mutate only part of it:
fn main() {
let (mut low, high) = (1, 10);
low += 4;
println!("{low}..{high}");
}This prints 5..10. Writing high += 1 would be rejected.
Mutable references
To let a function change the caller's variable, pass a mutable reference. A reference is a value that points to another value. The caller writes &mut to lend the variable out, and the function writes * to reach the value behind the reference.
fn add_one(n: &mut i32) {
*n += 1;
}
fn main() {
let mut value = 41;
add_one(&mut value);
println!("{value}");
}This prints 42. Both sides must opt in. The variable must be declared mut, and the call site must write &mut. If you forget mut on value, the compiler reports error[E0596]: cannot borrow value as mutable, as it is not declared as mutable. The explicit &mut at the call site means a reader can see which calls may change a variable.
Mutating collections and other types
Many standard-library operations change a value in place. Methods like push, insert, clear, and push_str take &mut self, so they need a mutable binding.
fn main() {
let mut names = Vec::new();
names.push(String::from("Ada"));
names.push(String::from("Grace"));
let mut label = String::from("users:");
label.push_str(" 2");
println!("{names:?} {label}");
}This prints ["Ada", "Grace"] users: 2. The compiler infers Vec<String> from the first push. If you drop mut from either binding, you get E0596.
This surprises people coming from languages where a const or final binding still permits changing an object's contents. In Rust, an immutable binding makes the whole value read-only. You cannot push to an immutable Vec, change a field of an immutable struct, or assign to an element of an immutable array.
fn main() {
let mut grid = [0u8; 3];
grid[1] = 7;
println!("{grid:?}");
let frozen = [0u8; 3];
// frozen[1] = 7; // error[E0594]: cannot assign to `frozen[_]`,
// // as `frozen` is not declared as mutable
println!("{frozen:?}");
}This prints [0, 7, 0] and [0, 0, 0]. The rule is deep. Mutability extends through the fields, elements, and owned contents of the value, though not through references to other data.
Deferred initialization
A binding does not need to be mutable if you only assign it once, later. The compiler tracks whether every path assigns it exactly once.
fn main() {
let label;
let score = 72;
if score >= 60 {
label = "pass";
} else {
label = "fail";
}
println!("{label}");
}This prints pass. There is one assignment on each path, so label does not need mut. This pattern often replaces a let mut that is set to a placeholder and then overwritten. Reading label before every path has assigned it is a compile error, so you cannot use an uninitialized variable by accident.
Freezing and thawing with shadowing
Mutability belongs to a binding, and you can create a new binding with different mutability. A common pattern is to build a value with a mutable binding, then shadow it with an immutable one so the rest of the function cannot change it.
fn main() {
let mut scores = vec![40, 90, 65];
scores.sort();
let scores = scores; // frozen from here on
// scores.push(100); // error[E0596]: cannot borrow `scores` as mutable
println!("{scores:?}");
}This prints [40, 65, 90]. The assignment let scores = scores; moves the vector into a new, immutable binding. Moving a value into a binding with different mutability is allowed when you own the value. The reverse also works: let mut v = v; turns a received immutable value into one you can modify.
Keeping mutation small
The compiler lets you declare everything mut, but doing so gives up some of the benefit of immutable defaults. These habits keep mutable state easy to follow:
- Declare a variable
mutonly when the compiler asks for it. If you add it and never modify the value, the compiler warnsvariable does not need to be mutable(theunused_mutlint). Treat that warning as a request to remove the keyword. - Keep the scope of a mutable binding as short as you can. Build the value inside a block and bind the result immutably.
- Prefer expressions that produce a value over loops that accumulate into a
mutvariable, when they read just as clearly.
fn main() {
// Accumulating with a mutable variable
let mut total = 0;
for n in 1..=4 {
total += n * n;
}
// The same result, bound immutably
let total_sum: i32 = (1..=4).map(|n| n * n).sum();
// A block limits where mutation is visible
let doubled = {
let mut v = vec![1, 2, 3];
for item in v.iter_mut() {
*item *= 2;
}
v
};
println!("{total} {total_sum} {doubled:?}");
}This prints 30 30 [2, 4, 6]. After the block, doubled is immutable, and the temporary mut binding v no longer exists.
Neither style is always better. A plain for loop with mut is idiomatic Rust and is often clearer than a long iterator chain. The point is to make the choice deliberately.
One writer at a time
Rust also restricts how many references may exist while a value is being modified. While a &mut reference to a value is alive, you cannot read or write that value through any other path. This is the borrowing rule that later chapters on ownership cover in detail. For now, you only need to see that it exists:
fn main() {
let mut text = String::from("hi");
let first = &mut text;
first.push('!');
// println!("{text}"); // would be an error here only if `first` were used again afterwards
println!("{first}");
}This prints hi!. The compiler tracks when a reference is last used, so once first is no longer needed, text is available again. If the commented line used text while first was still needed later, the compiler would reject it with E0502. This rule is what lets Rust prevent data races and invalidated references without a garbage collector.
Deciding whether to use mut
Common errors
| Compiler message | Cause | Fix |
|---|---|---|
| `E0384: cannot assign twice to immutable variable` | Reassigning a binding declared without `mut`. | Add `mut`, or shadow with a new `let`. |
| `E0596: cannot borrow ... as mutable, as it is not declared as mutable` | Calling a `&mut self` method, or taking `&mut`, on an immutable binding. | Declare the binding `mut`. |
| `E0594: cannot assign to ... as ... is not declared as mutable` | Assigning to a field or element of an immutable binding. | Declare the binding `mut`. |
| `E0308: mismatched types` | Assigning a value of a different type to a `mut` binding. | Shadow with `let`, or convert the value. |
| `E0502: cannot borrow ... as immutable because it is also borrowed as mutable` | Using a value while a `&mut` reference to it is still needed. | Finish using the reference first, or restructure. |
| `warning: variable does not need to be mutable` | `mut` on a binding that is never modified. | Remove `mut`. |
Exercises
Exercise
The code below fails to compile. Name the error code and give two different fixes: one that adds mut and one that does not.
fn main() {
let total = 10;
total = total + 5;
println!("{total}");
}
Show answer
The error is E0384, "cannot assign twice to immutable variable". Fix one: write let mut total = 10;, so the reassignment is allowed. Fix two: shadow the binding with let total = total + 5;, which creates a new immutable binding holding 15. Both print 15.
Exercise
Why does let mut label = "abc"; label = label.len(); fail, and how would you change the second statement so the program compiles?
Show answer
mut allows a new value but not a new type. label has type &str, and label.len() is a usize, so the assignment gives E0308 (mismatched types). Use shadowing instead: let label = label.len();. That creates a new binding of type usize.
Exercise
Given let v = vec![3, 1, 2];, how can you sort v without editing the let line, and keep the sorted result immutable afterwards?
Show answer
Shadow it with a mutable binding, sort it, then shadow it again with an immutable one: let mut v = v; v.sort(); let v = v;. Moving the vector into a new mut binding is allowed because you own it. The final let v = v; freezes it so later code cannot change it.