Sub topic 3
Opting into change with mut
This chapter assumes you can install Rust, run a program with cargo run or rustc, and read a simple compiler error. You should already know that a let binding is immutable by default. Here you will learn how mut changes that, what the compiler checks when you use it, and when it is the right choice.
What mut does
Adding mut after let marks the binding as changeable. You can then assign a new value to it as many times as you like, and you can use compound operators such as +=.
fn main() {
let mut count = 0;
println!("count = {count}");
count += 1;
count = count * 10;
println!("count = {count}");
}This prints count = 0 and then count = 10.
mut is a property of the binding, not of the value. The binding count is allowed to hold a different integer over time. The type does not change. Once count is inferred as i32, every later assignment must also be an i32.
fn main() {
let mut label = "start";
label = "done";
println!("{label}");
// label = 5; // error[E0308]: mismatched types
}Common errors
The most common error is forgetting mut. The compiler reports error E0384 and points at the second assignment.
fn main() {
let total = 0;
// total += 1; // error[E0384]: cannot assign twice to immutable variable `total`
println!("{total}");
}The fix is to write let mut total = 0;. The compiler also suggests this in its help text.
The opposite problem is a warning, not an error. If you write mut but never change the binding, the compiler warns variable does not need to be mutable. Treat this warning as useful. It tells you the binding could be immutable, and a reader will then know the value never changes.
fn main() {
let mut name = "Ferris"; // warning: variable does not need to be mutable
println!("{name}");
}Mutating through the binding
mut also controls whether you can modify a value in place, not only reassign it. A Vec is a growable list. Calling push changes the list, so the binding must be mut.
fn main() {
let mut scores = Vec::new();
scores.push(10);
scores.push(20);
println!("{scores:?}");
}This prints [10, 20]. Without mut, the call to push fails with error E0596, "cannot borrow scores as mutable, as it is not declared as mutable". The method needs a mutable borrow of the list, and an immutable binding does not allow one.
Declaring first and assigning later
You do not always need mut to set a value after the declaration. An immutable binding can be declared without a value and assigned exactly once. The compiler checks that every path assigns it before use.
fn main() {
let level;
let score = 70;
if score >= 50 {
level = "pass";
} else {
level = "retry";
}
println!("{level}");
}Each branch assigns level once, so no mut is needed. This is often clearer than a mut binding that starts with a placeholder value and is overwritten.
Choosing when to use mut
Prefer immutable bindings and add mut when the code needs it. The following table lists common cases.
| Situation | Suggested approach |
|---|---|
| A value is computed once and only read | Plain `let` |
| A value is chosen by a branch, then fixed | Declare, then assign once in each branch |
| A counter, accumulator, or buffer changes in a loop | `let mut` |
| A value is transformed in steps, possibly changing type | Shadowing with a new `let` (next chapter) |
| A collection grows or shrinks | `let mut` |
Keep the scope of a mut binding small. The shorter the stretch of code where a value can change, the less code you must read to know what it holds.
Exercises
Exercise
This program does not compile. What error does the compiler report, and what is the smallest change that fixes it? fn main() { let items = Vec::new(); items.push(1); println!("{items:?}"); }
Show answer
The compiler reports E0596: it cannot borrow items as mutable because the binding is not declared as mutable. Change the first line to let mut items = Vec::new();.
Exercise
Does the following code need mut on size? Explain why or why not.
fn main() {
let size;
if std::env::args().count() > 1 {
size = 10;
} else {
size = 20;
}
println!("{size}");
}
Show answer
No. size is declared without a value and assigned exactly once on each path, so the compiler accepts an immutable binding. Adding mut would trigger the "does not need to be mutable" warning.