Sub topic 9
The Borrowing Rules and the Borrow Checker
What this chapter assumes
You should already know how to create shared references (&T) and mutable references (&mut T), and how a move transfers ownership. This chapter covers the rules that decide which combinations of references the compiler accepts. It also covers how to read the errors when it rejects your code.
The two rules
Rust enforces two rules about references:
- At any moment, a value can have either any number of shared references (
&T) or exactly one mutable reference (&mut T), but not both. - A reference must always point to valid data. Rule 2 is the subject of the dangling references chapter.
Rule 1 is often summarized as "aliasing XOR mutation". Aliasing means several names reaching the same data. Mutation means changing it. Allowing both at once causes bugs in many languages:
- A reader sees half-updated data.
- An iterator is invalidated when the collection it walks is resized.
- Two threads write the same memory in a data race.
Rust forbids the combination, so these bugs become compile errors.
The checking program is the borrow checker. It runs at compile time and costs nothing at run time. It tracks every borrow, from where the reference is created to where it is last used, and reports a conflict if two borrows that overlap break rule 1.
A conflict you will meet often
This program tries to keep a reference into a vector while growing the vector:
fn main() {
let mut v = vec![1, 2, 3];
let first = &v[0];
v.push(4);
println!("{first}");
}It does not compile. The error is shown below, abbreviated:
error[E0502]: cannot borrow `v` as mutable because it is also borrowed as immutable
--> src/main.rs:4:5
|
3 | let first = &v[0];
| - immutable borrow occurs here
4 | v.push(4);
| ^^^^^^^^^ mutable borrow occurs here
5 | println!("{first}");
| ------- immutable borrow later used hereThe rule exists because push may reallocate the vector's buffer. If it did, first would point at freed memory. Rust cannot know whether push will reallocate, so it rejects every such program.
Read these messages in a fixed order:
- The error code and headline name the two conflicting borrows (
E0502: mutable versus immutable). - The first label shows where the earlier borrow starts.
- The second label shows the conflicting use.
- The last label shows where the earlier borrow is used again. That use is what keeps the borrow alive.
Borrows end at their last use
A borrow does not last until the end of the block. It lasts until the reference is last used. This is called non-lexical lifetimes. Moving the println! fixes the program above:
fn main() {
let mut v = vec![1, 2, 3];
let first = &v[0];
println!("{first}");
v.push(4);
println!("{:?}", v);
}After the first println!, first is never used again, so its borrow is over and push may take a mutable borrow. The program prints 1 and then [1, 2, 3, 4].
This only applies to plain references. If a value has a destructor that might use a reference, such as a struct implementing Drop, the borrow lasts until that value is dropped.
The states of a borrowed value
At any point, a value is in one of three states. The diagram shows how the state changes.
Two mutable borrows
Rule 1 also forbids a second &mut while the first is alive:
fn main() {
let mut s = String::from("hi");
let a = &mut s;
let b = &mut s;
a.push('!');
b.push('?');
}This fails with E0499: cannot borrow s as mutable more than once at a time. Both a and b are used after the second borrow starts, so their lifetimes overlap. If you finish with a before you create b, the code compiles.
The owner is restricted too
While a value is borrowed, the owner loses some of its abilities:
- With a live shared borrow, the owner can read the value but cannot mutate, move, or drop it.
- With a live mutable borrow, the owner cannot even read the value until the borrow ends.
Assigning to a variable that is borrowed is an error for the same reason. The borrow checker sees the owner as just another way of reaching the data.
Mutating through a shared reference
A &T never allows mutation. This is a separate error from the conflicts above. It happens when you call a method that takes &mut self through a shared reference, or when you declare a variable without mut and then take &mut of it. The compiler reports E0596: cannot borrow ... as mutable. The fix is to declare the variable mut, or to change the function parameter from &T to &mut T.
Borrowing parts of a value
The borrow checker tracks struct fields separately. Borrowing one field does not block use of another:
struct Player {
name: String,
score: u32,
}
fn main() {
let mut p = Player { name: String::from("Ada"), score: 0 };
let name = &p.name;
p.score += 1;
println!("{name} {}", p.score);
}This compiles and prints Ada 1. The compiler can see that the two fields are different places in memory.
It cannot do the same for indexing. v[0] and v[1] go through a method call, so the compiler treats both as borrowing all of v. When you need two mutable parts of a slice, ask the standard library for them:
fn main() {
let mut a = [1, 2, 3, 4];
let (left, right) = a.split_at_mut(2);
left[0] += right[0];
println!("{:?}", a);
}This prints [4, 2, 3, 4]. split_at_mut is written with unsafe inside, but its signature guarantees the two halves do not overlap.
Common ways to fix a borrow error
- Shorten the borrow. Use the reference earlier, or move the mutation after its last use, as in the
firstexample. - Copy out the data. Take
let first = v[0];for aCopytype, or call.clone(). You then hold your own value and no borrow remains. - Separate reading from writing. You cannot push to a vector inside a loop that iterates over it. Collect the changes first, then apply them:
fn main() {
let mut v = vec![1, 2, 3];
let extra: Vec<i32> = v.iter().map(|x| x * 10).collect();
v.extend(extra);
println!("{:?}", v);
}- Restructure the data. If two parts of a struct are always borrowed in different ways, put them in separate fields or separate structs.
Exercise
This code does not compile. Name the error code and the line that causes the conflict. Then give two different ways to fix it. let mut names = vec![String::from("a"), String::from("b")]; let last = names.last().unwrap(); names.push(String::from("c")); println!("{last}");
Show answer
The error is E0502. names.last() creates a shared borrow held by last. names.push(...) needs a mutable borrow while last is still used by the later println!. Fix 1: move the println!("{last}"); line above the push, so the shared borrow ends before the mutable one starts. Fix 2: take an owned copy with let last = names.last().unwrap().clone();. Then last is a String and does not borrow names, so the push is allowed.