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
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:
let mut s = String::from("hello");let r1 = &mut s;// let r2 = &mut s; // ERROR: cannot borrow s as mutable more than oncer1.push_str(" world");Shared and mutable references won't coexist either:
let mut s = String::from("hello");let r1 = &s; // shared borrowlet r2 = &s; // OK: another shared borrow// let r3 = &mut s; // ERROR: cannot borrow as mutable while shared refs existprintln!("{} {}", r1, r2);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.
Non-Lexical Lifetimes
The borrow checker has gotten cleverer about when a reference's life ends:
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 usedr2.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
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:
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);