Sub topic 2
Why bindings are immutable by default
This chapter assumes you can write and run a small Rust program with cargo run or rustc, and that you have seen let before. It also assumes you can read a compiler error. The previous chapter covered declaring variables. This one covers why Rust makes them read-only unless you ask otherwise, what that rule does and doesn't protect, and which errors you will meet.
What the rule says
A let binding in Rust is immutable unless you write let mut. After a value is bound to an immutable name, you cannot assign to that name again.
fn main() {
let x = 5;
println!("x = {x}");
// x = 6; // error[E0384]: cannot assign twice to immutable variable
let mut count = 0;
count += 1;
println!("count = {count}");
let total;
total = x + count;
println!("total = {total}");
}Uncomment x = 6; and the compiler rejects the program with E0384. It points at both assignments and suggests let mut x.
The rule has a precise scope. An immutable binding can be assigned exactly once. The assignment doesn't have to be in the let statement itself, as the total binding above shows. The compiler's job is to prove that every path through the code assigns the name at most once before it is read.
Deferred initialization
Deferred initialization is useful when the value depends on a branch:
fn main() {
let n = 7;
let label;
if n % 2 == 0 {
label = "even";
} else {
label = "odd";
}
println!("{n} is {label}");
}Each branch assigns label once, so the compiler accepts it without mut. If one branch forgot to assign, reading label afterwards would fail with E0381 (used binding is possibly-uninitialized). If you tried to assign twice on one path, you would get E0384.
This shows the rule is about assignment count, not about the keyword mut. Immutability here means "this name gets exactly one value".
Why Rust chooses this default
Rust could have copied languages where variables are writable by default. The designers chose otherwise for several connected reasons.
Reasoning about code
If a name is immutable, every use of it between its definition and the end of its scope sees the same value. You don't have to scan the function for assignments. When you see let mut, you know to look for changes. The keyword works as a marker for the places where state evolves.
Safety under aliasing
Rust's borrowing rules say that at any moment a value can have either many shared references (&T) or one exclusive mutable reference (&mut T), but not both. Immutability by default fits this model. Most bindings are read-only, so they can be freely shared and borrowed. Mutation becomes the rarer case that needs exclusive access.
The same property helps with threads. Data that nobody can change is safe to read from several threads without locks. The type system enforces the finer details with the Send and Sync traits, but read-only data is the easy case.
Optimization and intent
The compiler can make stronger assumptions about values that cannot change. Readers get a second benefit: a function signature or let statement states your intent. If a variable is mut and never modified, the compiler warns you:
warning: variable does not need to be mutableThat warning keeps the marker honest. A mut that stays in the code means something changes.
Making the cheap choice the safe one
Adding mut costs four characters, so the default is not hard to override. The default only changes which choice you make deliberately.
What immutability does and doesn't protect
An immutable binding blocks two things: assigning a new value to the name, and mutating the value through that name. Both are rejected, as this example shows:
fn main() {
let names = Vec::new();
names.push("ada"); // error[E0596]: cannot borrow `names` as mutable
println!("{}", names.len());
}push takes &mut self. Calling it needs a mutable borrow of names, and an immutable binding doesn't allow one. The fix is let mut names = Vec::new();.
The two errors you will see most often are related but distinct:
| Error | Trigger | Typical fix |
|---|---|---|
| `E0384` | Assigning to an immutable name a second time | Declare with `mut`, or shadow with a new `let` |
| `E0596` | Calling a `&mut self` method, or taking `&mut`, on an immutable binding | Declare the binding with `mut` |
| `E0594` | Assigning to a field of an immutable binding | Declare the binding with `mut` |
Mutability is part of the binding, not part of the value. The owner decides it, and ownership can move. This is legal:
fn main() {
let v = vec![1, 2, 3];
let mut w = v; // v is moved into w
w.push(4);
println!("{w:?}");
}The vector was never "immutable". The name v was. After the move, v can no longer be used, and the new owner w declared that it wants to change the data. Nobody else holds a handle, so this is safe.
Mutability flows down into fields
A struct has no per-field mutability keyword. Whether you can change a field depends on the binding that owns the struct.
struct Point {
x: i32,
y: i32,
}
fn main() {
let p = Point { x: 1, y: 2 };
// p.x = 10; // error[E0594]: cannot assign to `p.x`, as `p` is not declared as mutable
println!("{} {}", p.x, p.y);
let mut q = Point { x: 1, y: 2 };
q.x = 10;
println!("{} {}", q.x, q.y);
}If you have an immutable p, then all of p.x, p.y, and anything they own are read-only through p. If you have a mut q, then they are all writable. The same applies to tuples, arrays, and the contents of a Vec or String that the binding owns.
Bindings versus references
New Rust programmers often mix up mut on the binding with &mut on the type. They are independent:
| Declaration | Can the name be re-pointed? | Can the target be changed through it? |
|---|---|---|
| `let r = &x;` | No | No |
| `let r = &mut x;` | No | Yes |
| `let mut r = &x;` | Yes | No |
| `let mut r = &mut x;` | Yes | Yes |
The first column asks about the binding. The second asks about the type of the value the binding holds. In practice, the second row is the common way to hand out write access, and the third is rare.
Function parameters follow the same rule
Parameters are bindings, so they are immutable by default too. A mut in front of a parameter name makes that local binding writable inside the function. It does not change anything for the caller.
fn add_one(mut n: i32) -> i32 {
n += 1;
n
}
fn append_bang(s: &mut String) {
s.push('!');
}
fn main() {
let a = 1;
println!("{}", add_one(a));
println!("{a}");
let mut s = String::from("hi");
append_bang(&mut s);
println!("{s}");
}This prints 2, then 1, then hi!. add_one receives a copy of a, so its mut n only changes its own local. In append_bang, the &mut String type in the signature is what grants write access to the caller's string. The caller must also write &mut s, so the intent is visible at both ends of the call.
Deciding when to use `mut`
Start with an immutable binding and add mut when the compiler tells you to, or when you know the value genuinely changes: counters, accumulators, buffers you fill in a loop. Before reaching for mut, check two alternatives.
- If you are transforming a value in steps, a new
letwith the same name (shadowing) may be clearer. The next chapter covers it. - If a value is computed from a branch, use deferred initialization or make the
iformatchan expression:let label = if n % 2 == 0 { "even" } else { "odd" };.
Common pitfalls
- Adding
muteverywhere to silence errors. It works, but the compiler'sunused_mutwarning will point out the excess. Treat the warning as feedback. - Expecting
muton a reference to be enough. Writinglet mut r = &x;lets you re-pointr, not changex. To change the target you need&mut, andxitself must be declaredmut. - Assuming immutable means constant. An immutable binding can hold a value computed at runtime, and each run of a function creates a fresh one. A
constis a compile-time item with different rules, which a later chapter covers. - Assuming immutable means "no change is possible anywhere". Some types change through a shared reference. This is called interior mutability.
A first glance at interior mutability
The rule so far is that mutation requires mut. Some standard library types deliberately move that check from the binding to the type. Cell is the simplest:
use std::cell::Cell;
fn main() {
let counter = Cell::new(1);
counter.set(counter.get() + 1);
println!("{}", counter.get());
}counter is not mut, yet this prints 2. Cell::set takes &self, not &mut self, so an immutable binding can call it. Cell stays sound because it never hands out references to its contents. It only copies values in and out, so no one can observe a half-changed value through a reference.
Other types in this family, such as RefCell and Mutex, enforce the sharing rules at runtime instead. They exist for cases where the static rules are too strict. This is an overview only. For ordinary code, the default holds: if you want to change something, say mut.
Summary of the model
- A
letbinding is assigned exactly once unless declaredmut. - Mutability belongs to the binding, and it extends to fields and owned contents.
- Moving a value to a new owner lets the new binding choose its own mutability.
muton a parameter is local to the function.&mutin a type is what grants the caller's data to the callee for writing.- Interior mutability is the deliberate exception, built into specific types.
Exercise
This program fails to compile. Name the error code, say why it happens, and give two different fixes. fn main() { let items = Vec::new(); items.push(3); println!("{}", items.len()); }
Show answer
It fails with E0596: push takes &mut self, so it needs a mutable borrow of items, but items is an immutable binding. Fix 1: declare it with let mut items = Vec::new();. Fix 2: build the vector in one expression so no mutation is needed, for example let items = vec![3];.
Exercise
In the following code, which lines compile? Explain each answer. let a = 10; let mut b = a; b += 1; a += 1;
Show answer
let mut b = a; compiles because a is an i32, which is copied, so b is an independent mutable binding. b += 1; compiles because b is declared mut. a += 1; does not compile (E0384 or E0384-style "cannot assign twice to immutable variable") because a is immutable. Copying a into a mutable binding does not make a itself mutable.