What is the borrow checker?
Short answer: The borrow checker is the pass inside the Rust compiler that enforces the borrowing rules. It runs at compile time, before the program executes, and it is the component behind every borrow error in this chapter.
The pass behind those errors
Section titled “The pass behind those errors”Every borrow error in this chapter (E0502, E0499, E0597, and the E0382 from the first page) comes
out of the same pass. It is not a runtime check or a linter: the borrow checker is part of rustc
itself, so cargo build and cargo run all run it. When it rejects your code, nothing is produced
at all — no binary, no partial execution.
What it looks at
Section titled “What it looks at”Once the compiler has worked out every type, the borrow checker walks your function bodies,
tracking each reference: what it points at, shared or exclusive, and how long the value lives. It
then checks the two rules from
the rules page: at any moment a value has
either any number of & borrows or exactly one &mut, and every borrow must be valid. If any path
through the code could break a rule, the whole program is refused.
That is the guarantee: when the code compiles there is no dangling reference and no reader watching its value change — not because you tested those cases, but because the compiler checked every path.
The trade
Section titled “The trade”The price: it refuses some programs that would actually run correctly. Those are the subject
of the rest of this chapter: ending a borrow early, borrowing one field of a struct, taking a
reference instead of cloning. When the shape really does not fit, unsafe tells the compiler you
are taking over the checking — its own chapter, later. Fixing one borrow error often reveals
another behind it: not a change of mind, only compilation getting further.
rustc --explain E0502 prints the long form of any of them.
Related
Section titled “Related”- What are the rules of borrowing?
- Why does Rust allow many immutable borrows but only one mutable? — why the rules are what they are
- What does cargo check do? — the same check, no binary
- Borrowing — the rest of this chapter
- Next in this chapter: what is reborrowing?