Skip to main content
Be Bitwise
RustBorrowing & Lifetimes

Mutable References

Mutable references let you write through borrowed data. They come bundled with strict rules — exactly the rules that defang data races.

Creating Mutable References

rust
fn append_world(s: &mut String) {
s.push_str(", world!");
}
let mut s = String::from("hello");
append_world(&mut s);
println!("{}", s); // "hello, world!"

Two muts are mandatory: the binding declared mut, and the reference taken with &mut. Forget one, the compiler reminds you.

The Exclusivity Rule

At most one mutable reference is alive at a time:

rust
let mut s = String::from("hello");
let r1 = &mut s;
// let r2 = &mut s; // ERROR: cannot borrow s as mutable more than once
r1.push_str(" world");

Shared and mutable references won't coexist either:

rust
let mut s = String::from("hello");
let r1 = &s; // shared borrow
let r2 = &s; // OK: another shared borrow
// let r3 = &mut s; // ERROR: cannot borrow as mutable while shared refs exist
println!("{} {}", r1, r2);
Key Concept

The exclusivity rule kills data races at the type level. Picture two threads — one reading through &s, the other writing through &mut s. Without exclusivity, the reader could observe a half-mutated value. Rust forecloses on the entire failure mode by construction.

The same rule catches iterator invalidation. In C++, a push_back inside a range-for over the same vector can reallocate the buffer and leave the loop reading freed memory. Rust stops it at compile time: the loop holds a shared borrow of v for its whole run, so v.push asks for a mutable borrow at exactly the wrong moment.

Try itUncomment the loop and read the E0502 error, which points at both borrows.
Rust (1.40.0)

Non-Lexical Lifetimes

The borrow checker has gotten cleverer about when a reference's life ends:

rust
let mut s = String::from("hello");
let r1 = &s;
println!("{}", r1); // r1's last use - borrow ends here
let r2 = &mut s; // OK: no conflict because r1 is no longer used
r2.push_str(" world");

A reference dies at its final use, not at the closing brace of its block. The feature has a name: non-lexical lifetimes (NLL). It arrived with the 2018 edition and reached 2015-edition code in Rust 1.36, which is why so much "obviously fine" code stopped getting flagged.

Mutable References in Loops

rust
let mut numbers = vec![1, 2, 3, 4, 5];
for n in &mut numbers {
*n *= 2;
}
println!("{:?}", numbers); // [2, 4, 6, 8, 10]

&mut numbers borrows the whole vector mutably. Inside the loop, n is a &mut i32 pointing at the current element.

Pattern: Builder Methods

Mutable references make the builder pattern fall out naturally:

rust
struct Config {
debug: bool,
verbose: bool,
threads: usize,
}
impl Config {
fn new() -> Self {
Config { debug: false, verbose: false, threads: 1 }
}
fn debug(&mut self, val: bool) -> &mut Self {
self.debug = val;
self
}
fn threads(&mut self, n: usize) -> &mut Self {
self.threads = n;
self
}
}
let mut config = Config::new();
config.debug(true).threads(4);