The Analogy: The Reading Room
A research library holds a manuscript that never leaves the building -- the library owns it, permanently. What you can do is request it to a desk in the reading room and read it there. And here is the useful part: ten scholars can crowd round the same open page and all read at once. Nothing goes wrong, because reading changes nothing. There is no queue, no ticket, no contention. Ten readers or one, the manuscript says the same thing.
Now suppose one scholar has permission to annotate it in pencil. While that is happening, nobody else may look at it -- not even to read. That is not the librarian being territorial. A half-written annotation is not a fact yet: a second scholar copying a sentence mid-edit would faithfully copy something that was never true, and would have no way to know. So annotation is exclusive by construction. One pencil, zero other readers, and when the pencil goes down everyone can come back.
There is one more rule, and it is the one nobody argues with. Your reading slip is void the moment the manuscript ceases to exist. If the item is deaccessioned, every slip referring to it is waste paper, and the librarian will simply not issue a slip that outlasts the item it names. A slip pointing at nothing is worse than no slip, because it looks valid.
Rust calls the reading slip a shared reference, written &T, and you may hold any number. It calls the pencil a mutable reference, &mut T, and while one exists no other reference of either kind may. The third rule is that no reference may outlive the value it points to. All three are checked by the compiler, at compile time, with no run-time cost -- so "someone read it while it was half-written" (a data race) and "someone read it after it was destroyed" (a use-after-free) are not hazards you test for and hope to catch. They are shapes of program that do not build.
Syntax or Core Structure
Borrowing is two sigils, & and &mut, and one operator, *. That is the whole surface area.
fn main() {
let mut text = String::from("hello");
// A shared reference. Read-only, and you may take as many as you like.
let r1 = &text;
let r2 = &text;
println!("r1 = {r1}, r2 = {r2}, len = {}", r1.len());
// Nothing moved, so the owner is untouched.
println!("owner still has: {text}");
// A mutable reference. Exclusive, and the owner must be declared `mut`.
let m = &mut text;
m.push_str(", world");
println!("through m: {m}");
// Once m is finished with, the owner is readable again.
println!("owner now: {text}");
// Functions borrow exactly the same way.
println!("words = {}", count_words(&text));
shout(&mut text);
println!("after shout: {text}");
// `*` dereferences when you want the value rather than the reference.
let n = 41;
let p = &n;
println!("p = {p}, *p + 1 = {}", *p + 1);
}
fn count_words(s: &str) -> usize {
s.split_whitespace().count()
}
fn shout(s: &mut String) {
s.make_ascii_uppercase();
s.push('!');
}
Output:
r1 = hello, r2 = hello, len = 5
owner still has: hello
through m: hello, world
owner now: hello, world
words = 2
after shout: HELLO, WORLD!
p = 41, *p + 1 = 42
Notice count_words(&text): the parameter is &str but the argument is &String, and it compiles because of deref coercion. That is not a special case for strings -- &Vec<T> becomes &[T] and &Box<T> becomes &T the same way -- and it is why &str is the right parameter type even when every caller you can imagine has a String.
Now the three ways to get it wrong, because these diagnostics are the rules. First, a shared reference that is still needed while the owner is mutated:
fn main() {
let mut text = String::from("hello");
let r = &text;
text.push_str(" world");
println!("r = {}", r);
}
Output (compile error):
error[E0502]: cannot borrow `text` as mutable because it is also borrowed as immutable
--> src/main.rs:4:5
|
3 | let r = &text;
| ----- immutable borrow occurs here
4 | text.push_str(" world");
| ^^^^^^^^^^^^^^^^^^^^^^^ mutable borrow occurs here
5 | println!("r = {}", r);
| - immutable borrow later used here
Second, two mutable references at once:
fn main() {
let mut text = String::from("hello");
let a = &mut text;
let b = &mut text;
a.push('!');
println!("{b}");
}
Output (compile error):
error[E0499]: cannot borrow `text` as mutable more than once at a time
--> src/main.rs:4:13
|
3 | let a = &mut text;
| --------- first mutable borrow occurs here
4 | let b = &mut text;
| ^^^^^^^^^ second mutable borrow occurs here
5 | a.push('!');
| - first borrow later used here
Third, a reference that would outlive its value:
fn dangle() -> &String {
let s = String::from("gone");
&s
}
Output (compile error, trimmed):
error[E0106]: missing lifetime specifier
--> src/main.rs:1:16
|
1 | fn dangle() -> &String {
| ^ expected named lifetime parameter
|
help: this function's return type contains a borrowed value, but there is no
value for it to be borrowed from
That third one is worth dwelling on, because the obvious fix does not work. Add a lifetime -- fn dangle<'a>() -> &'a String -- and the error simply relocates to error[E0515]: cannot return reference to local variable. There is no way to write this function, and that is deliberate: s is dropped at the closing brace, so any reference to it is a slip for a manuscript that has been shredded. The fix is to return the String itself and hand over ownership.
Technical Depth: The Two Rules, and What They Actually Buy You
The rules, stated precisely
At any point in the program, for any given value, you may have either any number of shared references &T or exactly one mutable reference &mut T -- never both. And no reference may outlive the value it refers to.
That is often taught as "the borrow checker is strict about mutation", which misses the point. The rule forbids aliasing plus mutation, and aliasing plus mutation is the precondition for an entire catalogue of bugs:
| Shape the rule forbids | Bug it would otherwise be |
|---|---|
A & alive while a &mut writes | Reading a half-updated value; a data race, if the two are on different threads |
Two &mut to the same value | Lost updates, with no defined ordering between the writers |
| A reference that outlives its owner | Use-after-free; a pointer that looks valid and is not |
A & into a Vec across a push | A dangling pointer, because push may reallocate and move the buffer |
The last row is the sharpest illustration. v.push(x) can outgrow the current allocation, allocate a bigger one, copy the elements across, and free the old buffer. Any &v[0] taken beforehand now points into freed memory. This is not a hypothetical -- it is exactly the C++ "iterator invalidation" family, and in Rust it is error[E0502] instead of a crash on a Tuesday.
Borrows end at their last use, not at the closing brace
This is the detail that decides whether Rust feels workable. Since the 2018 edition the borrow checker uses non-lexical lifetimes: a borrow's region ends after its final use, not at the end of the enclosing block. So this compiles:
let mut v = vec![1, 2, 3];
let first = &v[0];
println!("first = {first}");
v.push(4); // fine: `first` was last used above
println!("{v:?}");
and moving the push one line earlier does not. If you have read older Rust advice about restructuring code into inner blocks to end borrows, that advice is obsolete; write the natural order and the checker follows it.
The two reference types are not symmetrical
| Type | Is it Copy? | How many at once | Can write through it |
|---|---|---|---|
&T | Yes | Any number | No |
&mut T | No | Exactly one | Yes |
&mut T not being Copy is what enforces exclusivity -- if you could copy it, "exactly one" would be unenforceable. But that raises an obvious question: how can you pass the same &mut to two functions in a row without moving it? The answer is implicit reborrowing. When a &mut T is passed where a &mut T is expected, the compiler inserts &mut *m rather than moving m, so the original is usable again once the callee returns. Similarly, a &mut T coerces to a &T wherever a shared reference is wanted.
Auto-reference at method calls, and coercion at call sites
You almost never write & before a method call, because the compiler inserts it: text.len() becomes str::len(&text) and v.push(x) becomes Vec::push(&mut v, x). That second one is why v must be declared mut -- the &mut you never typed is still a &mut. Deref coercion then handles the other direction at call sites:
&Stringwhere&stris wanted.&Vec<T>where&[T]is wanted.&mut Vec<T>where&mut [T]is wanted.&Box<T>where&Tis wanted.
Taking the coerced-to type in your signatures is free and strictly more general, which is why clippy's ptr_arg lint fires on fn f(s: &String).
Disjoint fields can be borrowed separately
The borrow checker reasons about paths, not whole variables, so two different fields of one struct can be mutably borrowed at the same time:
struct Account {
owner: String,
balance: i64,
}
fn describe(a: &Account) -> String {
format!("{} has {}", a.owner, a.balance)
}
fn deposit(a: &mut Account, amount: i64) {
a.balance += amount;
}
fn initial(s: &str) -> Option<char> {
s.chars().next()
}
fn main() {
let mut acct = Account { owner: String::from("ada"), balance: 100 };
// Many shared borrows at once.
let x = &acct;
let y = &acct;
println!("{} / {}", describe(x), describe(y));
// One mutable borrow, created and finished within the call.
deposit(&mut acct, 50);
println!("{}", describe(&acct));
// A &mut is not Copy, but passing it reborrows rather than moving it,
// so `m` is still usable after each call.
let m = &mut acct;
deposit(m, 10);
deposit(m, 10);
println!("{}", describe(m));
// Disjoint field paths can be mutably borrowed simultaneously.
let name = &mut acct.owner;
let bal = &mut acct.balance;
name.push_str(" lovelace");
*bal *= 2;
println!("{} / {}", name, bal);
// Deref coercion: &String is accepted where &str is wanted.
println!("initial = {:?}", initial(&acct.owner));
}
Output:
ada has 100 / ada has 100
ada has 150
ada has 170
ada lovelace / 340
initial = Some('a')
The two deposit(m, ...) calls are the reborrow rule made visible: if &mut behaved like a normal move, the second call would fail. And the name/bal pair only works because they are different paths. Two methods that each take &mut self cannot be interleaved the same way, however true it is that they touch different fields -- the signature says "all of me". That asymmetry is why the standard library provides split_at_mut and iter_mut: they hand out several disjoint &mut from one &mut self in a way the checker can verify.
Real World Example: Sanitising Records In Place
Cleaning up a batch of rows is the job where borrowing earns its keep. The caller has the data and wants to keep it; the sanitiser needs to change it; and a reader afterwards wants to point into it without copying anything out.
struct Record {
id: u32,
email: String,
score: i32,
}
#[derive(Debug, Default)]
struct Fixes {
trimmed: usize,
lowercased: usize,
clamped: usize,
}
/// Reads only. The caller keeps the data, and the returned reference points
/// straight into it -- nothing is copied.
fn worst(records: &[Record]) -> Option<&Record> {
records.iter().min_by_key(|r| r.score)
}
/// Writes in place. One `&mut` for the whole pass, and no second Vec.
fn sanitise(records: &mut [Record]) -> Fixes {
let mut fixes = Fixes::default();
for r in records.iter_mut() {
if r.email.trim().len() != r.email.len() {
let fixed = r.email.trim().to_string();
r.email = fixed;
fixes.trimmed += 1;
}
if r.email.chars().any(|c| c.is_ascii_uppercase()) {
r.email.make_ascii_lowercase();
fixes.lowercased += 1;
}
if r.score > 100 {
r.score = 100;
fixes.clamped += 1;
} else if r.score < 0 {
r.score = 0;
fixes.clamped += 1;
}
}
fixes
}
fn main() {
let mut records = vec![
Record { id: 1, email: String::from(" Ada@Example.COM "), score: 118 },
Record { id: 2, email: String::from("linus@example.com"), score: 74 },
Record { id: 3, email: String::from("Grace@Example.com"), score: -5 },
];
let fixes = sanitise(&mut records);
println!("{fixes:?}");
for r in &records {
println!("{} {:<20} {}", r.id, r.email, r.score);
}
match worst(&records) {
Some(r) => println!("worst = id {} at {}", r.id, r.score),
None => println!("worst = none"),
}
}
Output:
Fixes { trimmed: 1, lowercased: 2, clamped: 2 }
1 ada@example.com 100
2 linus@example.com 74
3 grace@example.com 0
worst = id 3 at 0
Two signatures, two contracts, and the caller keeps the vector either way. sanitise takes &mut [Record] and rewrites the rows where they sit -- no second Vec is allocated, no Record is cloned, and records is still there afterwards for the loop and for worst to read. Compare that with the reflex of returning a new collection: correct, easy, and it doubles peak memory for a job that changes three fields.
worst is the more interesting half. It returns Option<&Record> -- a reference into the caller's vector -- and lifetime elision quietly ties that reference's lifetime to the input slice, so the compiler knows the result may not outlive records. This is where the borrow rule stops being a restriction and starts being a feature: try holding the result of worst and then calling records.push(...), and you get error[E0502], because push may reallocate the buffer and leave your reference pointing at freed memory. The alternative design -- returning an owned Record -- would be a clone per call, forever, to avoid a bug the compiler can simply prevent.
The ordering in main is not arbitrary and cannot be shuffled, which is exactly the guarantee you want. sanitise(&mut records) needs exclusive access, so it cannot overlap with the printing loop or with worst. Because borrows end at their last use, the exclusive borrow expires the instant sanitise returns, so the code reads top to bottom with no ceremony -- but "render the table while the sanitiser is halfway through row two" is not a race you have to reason about, it is a program that does not compile.
One deliberate choice worth copying: the parameters are &[Record] and &mut [Record], not &Vec<Record> and &mut Vec<Record>. Deref coercion means a Vec caller writes &records and &mut records exactly as they already do, but now an array, a boxed slice, or a sub-slice such as &mut records[1..] works too. Taking the most general reference type costs nothing at the call site and widens what the function accepts, which is precisely what clippy's ptr_arg lint is nudging you towards.
Common Mistakes
- Mutating the owner while a shared reference is still needed.
let r = &v; v.push(1); println!("{r:?}");iserror[E0502]. Read the third underline -- "immutable borrow later used here" -- because that is the line you can usually move, and moving it is the whole fix.
- Two mutable references at once.
error[E0499]. If the two really do touch different parts of the data, say so with paths (&mut s.aand&mut s.b) or withsplit_at_mut, rather than reaching forRefCell.
- Forgetting
muton the owner.let s = String::new(); let r = &mut s;giveserror[E0596]: cannot borrow s as mutable, as it is not declared as mutable. The mutability lives on the binding, not on the reference type alone.
- Trying to write through a shared reference.
let r = &n; *r = 5;giveserror[E0594]: cannot assign to *r, which is behind a & reference.&Tis a reading slip; there is no version of it that writes.
- Returning a reference to a local.
E0106first, thenE0515if you add a lifetime. Every attempt fails, because none of them can make the local outlive the function. Return the owned value.
- Holding a reference into a
Vecacross a resize.push,insert,extend,reserve, andremovecan all move the buffer. Take the index instead of the reference if you need to survive a resize.
- Writing
&Stringor&Vec<T>parameters. It compiles, and it turns away every caller holding a&str, a literal, an array, or a sub-slice. Use&strand&[T]; clippy'sptr_argwill remind you.
- Forgetting the
*when comparing or assigning through a reference.if r == 5wherer: &i32fails, because&i32andi32are different types. Write*r == 5, orr == &5if that reads better.
- Restructuring code into inner blocks to end a borrow. That was necessary before the 2018 edition. Today borrows end at their last use, so the extra braces are noise -- write the straightforward order and only investigate if the checker actually objects.
Best Practices
- Default to
&Tin parameters, upgrade to&mut Twhen the function must change something, and take by value only when it must keep or consume it. Signatures in that order are self-documenting.
- Prefer the coerced-to types:
&strover&String,&[T]over&Vec<T>,&mut [T]over&mut Vec<T>. Reserve&Vec<T>for the rare function that genuinely needscapacityorreserve.
- Return owned values from public functions unless handing back a reference is the point. A returned reference imports the caller's lifetime questions into your API.
- When
E0502fires, look for a line to move before looking for something to clone. The borrow usually ends one line later than it needs to.
- Borrow disjoint fields by path when you need two mutable views of one struct, and use
split_at_mutoriter_mutfor slices. Reach forRefCellonly when the sharing pattern genuinely cannot be expressed statically.
- Keep mutable borrows short. A
&mutthat spans forty lines is a lock held for forty lines, and it will eventually collide with something you want to read.
- Store indices rather than references when the collection may be resized between uses. An index survives a reallocation; a reference does not, and the compiler will make you prove you knew that.
- Let the compiler insert
&and&mutat method calls, but remember it is doing so. Whenv.push(x)demandsmut v, that is the invisible&muttalking.
Practice Exercises
- Provoke all four errors. Write one small program per diagnostic and record the exact code and message for
E0502,E0499,E0596, andE0594. For each, write the smallest fix that keeps the intent -- not the fix that deletes the feature.
- Count without copying. Write
fn stats(samples: &[f64]) -> (f64, f64, f64)returning min, max, and mean in a single pass, thenfn normalise(samples: &mut [f64])that rescales every value into 0.0 to 1.0 in place. Callstatsbefore and after and confirm the second call reports 0.0, 1.0, and something between.
- Make the dangling reference impossible. Start from
fn longest_word(text: &str) -> &strand get it compiling with no explicit lifetime annotations. Then try to write a version that builds aStringinside the function and returns a slice of it, read the error, and explain in one sentence why elision cannot save you.
- Break the sanitiser deliberately. In the
Recordexample, try each of these and note the error code: callingworst(&records)first and printing the result aftersanitise(&mut records); pushing a fourth record while holding the result ofworst; changingsanitiseto take&[Record]; and taking&mut r.emailand&mut r.scoreat the same time inside the loop (this one should work -- explain why).