Skip to content
Theory · Borrowing · lesson 5 of 11

One writer or many readers

Now you have two kinds of references: for reading and for writing. How many of them can you hand out at once?

Back to the book. Several friends can read it at the same time: they look at the same pages and do not get in each other's way. But if someone has taken the book to make notes, nobody may read it meanwhile: a reader would see a half-written sentence. Two writers at once will not do either — their notes would pile on top of each other.

The borrowing rule

Every reference in a program is checked by a part of the compiler, the borrow checker. Its main rule: at any moment a value has

  • either any number of & references;
  • or exactly one &mut reference, and while it is alive, nobody else touches the value, not even the owner.

This rule is the best-known one in Rust, and interviewers like to ask about it: "How many references to a value can exist at the same time?"

Many readers

A & reference is also called a shared reference. There can be any number of them, and the owner can read meanwhile too:

Rust
fn main() {
    let s = String::from("Dune");
    let r1 = &s;
    let r2 = &s;
    println!("{r1} {r2} {s}"); // Dune Dune Dune
}

All three only read, so the program builds and prints Dune Dune Dune.

One writer

The compiler does not let two mutable references to one value through:

Rust
fn main() {
    let mut s = String::from("hi");
    let w1 = &mut s;
    let w2 = &mut s; // ✗
    w1.push('!');
    w2.push('?');
}
TEXT
error[E0499]: cannot borrow `s` as mutable more than once at a time

When w2 is created, the reference w1 is still needed: the next line calls push through it. That makes two writers at once, and it is a compile error, not a panic: the program does not even build.

A borrow ends at its last use

So when does a reference let go of the value? Not at the block's }, but at the last place where the reference is used. The reference's name is still visible in the code after that, but the compiler knows it is no longer needed and allows other borrows again.

Step through the program and watch the label on the main frame: it shows who is holding the string right now.

LiveWho holds the stringstep 1 of 11 · frames: 1

s owns the string hi, and there are no references to it yet.

Watch where each reference is used for the last time

Let's go over what happened:

  1. r1 and r2 are used for the last time on line 5, and their borrow ends right there.
  2. That is why line 6 can take &mut s: there are no readers left.
  3. The reference w is used for the last time on line 8, and from there the owner reads s by itself again.
  4. On line 10 a new reader r3 appears: the writer is done.

If you print r1 once more after w.push('!'), the borrow of r1 stretches to that print and overlaps w. Then the compiler stops at line 6 with error E0502.

Here the book analogy falls short. In real life a reader returns the book whenever they decide to. In Rust nobody returns anything: the compiler finds the last use of each reference in the code by itself. The whole check happens at build time, and the running program spends no time on it.

Why this rule exists

A reader counts on the value not changing while it looks at it. The rule guarantees that: if the reference r showed the string hi, it keeps showing hi as long as r is alive. In C and C++ the compiler does not check this: the value can be changed through another name while it is read through a reference.

Common mistake

The string is changed while a reference looks at it, and then that reference is read:

Rust
fn main() {
    let mut s = String::from("hi");
    let r = &s;
    s.push('!'); // ✗
    println!("{r}");
}
TEXT
error[E0502]: cannot borrow `s` as mutable because it is also borrowed as immutable

s.push('!') takes a mutable reference to s, while r is still alive: it is printed on the next line. A reader and a writer have met, and the compiler refuses. The fix is to finish reading before the change: move println!("{r}"); above s.push('!').

Key points

  • At any moment a value has either any number of & references or exactly one &mut.
  • Two live &mut give error E0499, and a & together with a change gives E0502; the compiler catches both.
  • A borrow ends at the reference's last use, not at the block's }.
  • The rule keeps a value from changing while a reader looks at it.