Sub topic 4
The borrowing rules: many readers or one writer
This chapter covers the single rule behind most borrow checker errors. It assumes you can write basic Rust, know the difference between String and &str, and have read the earlier chapters on moves, &T, and &mut T.
The rule
At any point in a program, a value can be accessed in one of two ways:
- Through any number of shared references (
&T), which are read-only. - Through exactly one mutable reference (
&mut T), which can read and write.
You cannot have both at once. Many readers, or one writer.
The rule applies to references that are still in use, not to every reference that exists. A later chapter covers exactly where a borrow ends. For now, read "alive" as "used again later in the function".
The rule has three cases:
| Situation | Allowed? |
|---|---|
| Two `&T` to the same value | Yes |
| One `&mut T`, nothing else | Yes |
| `&T` and `&mut T` alive together | No |
| Two `&mut T` alive together | No |
The diagram shows the states a value moves through as borrows start and end.
There is no arrow from SharedBorrowed to MutBorrowed. You must reach Free first.
Why the rule exists
A data race needs three ingredients: two or more pointers to the same data, at least one that writes, and no synchronization. Rust's rule removes the first two ingredients from the same combination. A writer is never alongside other pointers.
The same rule prevents bugs in single-threaded code. The classic one is invalidation. A shared reference points into a vector's buffer, and then a push reallocates that buffer. The reference now points at freed memory. In C++ this is undefined behavior. In Rust it is a compile error.
Shared and mutable borrows conflicting
This program does not compile:
fn main() {
let mut v = vec![1, 2, 3];
let first = &v[0];
v.push(4);
println!("{first}");
}The compiler reports error E0502: cannot borrow v as mutable because it is also borrowed as immutable. The shared borrow first is created on line 3. v.push(4) needs &mut v on line 4. first is used on line 5, so the shared borrow is still alive when the mutable one starts.
push may reallocate the buffer, so first could dangle. The compiler rejects the program without knowing whether reallocation would actually happen.
Two mutable borrows conflicting
Two writers are also rejected. This does not compile:
fn main() {
let mut s = String::from("a");
let r1 = &mut s;
let r2 = &mut s;
r1.push('b');
r2.push('c');
}The error is E0499: cannot borrow s as mutable more than once at a time. The compiler points at both borrows and at the later use of the first.
Using the owner during a mutable borrow
The owner is locked while a mutable reference is alive. This does not compile:
fn main() {
let mut s = String::from("a");
let m = &mut s;
println!("{s}");
m.push('b');
}println! takes a shared borrow of s, which conflicts with m, so you get E0502 again. Assigning to the owner (s = String::new();) while a reference is alive gives E0506: cannot assign to s because it is borrowed.
Fixing conflicts by ending a borrow sooner
Often you can fix a conflict by finishing with one borrow before starting the next. This compiles:
fn main() {
let mut s = String::from("a");
let r = &s;
println!("{r}");
let m = &mut s;
m.push('b');
println!("{m}");
}r is last used in the first println!. After that it no longer counts, so &mut s is allowed. The compiler tracks this by looking at where each reference is used, not at curly braces. You can still add an explicit { ... } block, but it is rarely needed in modern Rust.
Common error: changing a collection while looping over it
A for loop over &v holds a shared borrow for the whole loop. This does not compile:
fn main() {
let mut v = vec![1, 2, 3];
for x in &v {
if *x == 2 {
v.push(4);
}
}
}The error is E0502, and the shared borrow comes from the loop's iterator. There are several fixes. The right one depends on what you want:
- Collect the changes first, then apply them after the loop.
- Loop over indices (
for i in 0..v.len()) if you only need to read and write one element at a time. - Use
v.retain(...)orv.iter_mut()when you are modifying or removing elements in place. - Loop over a clone if the collection is small and clarity matters more than cost.
The first fix looks like this:
fn main() {
let mut v = vec![1, 2, 3];
let extra: Vec<i32> = v
.iter()
.filter(|&&x| x == 2)
.map(|x| x + 2)
.collect();
v.extend(extra);
println!("{v:?}");
}The iterator borrows v only until collect finishes. After that, v.extend has the vector to itself. The program prints [1, 2, 3, 4].
Two mutable borrows of different data
The rule applies to overlapping data. The compiler can see that two struct fields do not overlap, so this compiles:
struct Point {
x: i32,
y: i32,
}
fn main() {
let mut p = Point { x: 1, y: 2 };
let rx = &mut p.x;
let ry = &mut p.y;
*rx += 10;
*ry += 20;
println!("{} {}", p.x, p.y);
}This works only when you name the fields directly. A method taking &mut self borrows the whole struct, so you cannot call two such methods and keep both results alive. Indexing has the same limit. The compiler does not know that v[0] and v[1] are different elements, so &mut v[0] and &mut v[1] together are rejected. The standard library offers split_at_mut for this case, and it returns two non-overlapping mutable slices.
Common error: the writer is taken first
Order matters. A mutable borrow is fine if nothing else is alive, so check whether a leftover reference is the real problem. A typical error report looks like this:
- The compiler shows where the first borrow is created and its kind (immutable or mutable).
- It shows the conflicting second borrow.
- It shows the later use that keeps the first borrow alive.
The third point is the one to act on. Remove that later use, move it earlier, or copy the data out of the reference before the conflicting borrow. For example, let n = v[0]; copies an i32, so no borrow remains. let first = v[0].clone(); does the same for a type that is not Copy.
What the rule does not cover
The borrowing rules say nothing about ownership transfer. Moving a value into a function is a separate matter. They also do not say how long a reference may live, which is the job of lifetimes (a later chapter). Some programs are correct but still rejected, because the check is conservative. When the data really must be changed through shared references, RefCell moves the same rule to run time. Using it wrongly causes a panic instead of a compile error. That is covered in a later chapter, and it is a last resort here.
Summary of the working model
- Every use of a value is either a read through shared access or a write through exclusive access.
- Shared access can overlap with other shared access. Exclusive access overlaps with nothing, including the owner.
- A borrow lasts from its creation to its last use.
- To fix a conflict, shorten one borrow, copy data out, or restructure so the accesses do not overlap.
Exercise
This function does not compile. Which error code does the compiler report, and what is one change that fixes it without cloning? fn main() { let mut names = vec![String::from("ann"), String::from("bo")]; let first = &names[0]; names.push(String::from("cy")); println!("{first}"); }
Show answer
It reports E0502 (cannot borrow names as mutable because it is also borrowed as immutable). Move the println!("{first}"); line above names.push(...), so the shared borrow first is no longer used when the mutable borrow starts. Both borrows then do not overlap.
Exercise
Why does let a = &mut v[0]; let b = &mut v[1]; fail to compile for a Vec<i32>, even though the two elements are different memory locations? Name a standard library method that provides two mutable references to different parts.
Show answer
Indexing goes through IndexMut::index_mut, which borrows the whole vector mutably, and the compiler does not reason about which index is used. The first borrow therefore covers all of v, and the second conflicts with it (E0499). split_at_mut returns two non-overlapping mutable slices, so you can take one element from each.