Sub topic 4
The Borrowing Rules: Many Readers or One Writer
This chapter assumes you can write basic Rust, know String and Vec, and have seen &T and &mut T used in function parameters. Here you will learn the single rule that ties both kinds of reference together, and what the compiler does when you break it.
The rule
At any point in a program, a value can have either of these, but never both:
- any number of shared references (
&T), or - exactly one mutable reference (
&mut T).
This is often called "shared XOR mutable". The compiler checks it at compile time, so a program that breaks it does not build.
Why the rule exists
Aliasing means two names reach the same data. Mutation means changing that data. Either one is safe alone. Together they cause trouble: one name changes the data while another name is still reading it.
A Vec shows this well. Pushing onto a vector may allocate a larger buffer and move the elements. A reference to an old element would then point to freed memory. The same pattern, across threads, is a data race. The borrowing rule removes both problems with one check.
A rejected program
fn main() {
let mut v = vec![1, 2, 3];
let first = &v[0];
v.push(4);
println!("{first}");
}This does not compile. The compiler reports error E0502: it cannot borrow v as mutable because it is also borrowed as immutable.
Three events matter here:
&v[0]creates a shared borrow, stored infirst.v.push(4)needs a mutable borrow ofv.println!usesfirstafterwards, so the shared borrow is still alive at step 2.
The overlap in step 2 breaks the rule.
Fixing it
The fix is to make the borrows not overlap. Finish using the reader before the writer starts:
fn main() {
let mut v = vec![1, 2, 3];
let first = &v[0];
println!("{first}");
v.push(4);
println!("{:?}", v);
}This compiles because first is last used before push. The compiler tracks where each borrow is last used, not where the variable goes out of scope. The next chapters return to this point.
Many readers are fine
Shared references never conflict with each other:
fn main() {
let s = String::from("hello");
let a = &s;
let b = &s;
println!("{a} {b} {}", s.len());
}Even the owner s can be read while a and b exist, because reading through s counts as another shared use.
Two writers are not fine
fn main() {
let mut s = String::from("hi");
let a = &mut s;
let b = &mut s;
a.push('!');
b.push('?');
}This fails with error E0499: it cannot borrow s as mutable more than once at a time. The same holds when the owner itself is touched while a mutable borrow is live. While a is active, s should not be read or written directly.
Common mistakes
| Situation | Result |
|---|---|
| Two or more `&T` at once | Allowed |
| One `&mut T` alone | Allowed |
| `&T` and `&mut T` overlapping | Error E0502 |
| Two `&mut T` overlapping | Error E0499 |
When you see E0502 or E0499, look for the earlier borrow and the later use. Then either move the later use up, shorten the borrow, or restructure the code so only one kind of access happens at a time.
Exercise
Why does the compiler accept let r = &s; println!("{r}"); let m = &mut s; m.push('b'); but reject the same code if println!("{r}") comes after let m = &mut s;?
Show answer
In the accepted version, the shared borrow r is last used before the mutable borrow m starts, so the two never overlap. In the rejected version, r is still used while m exists, so a shared and a mutable borrow overlap, which breaks the rule and gives error E0502.