What Does Rust's Borrow Checker Actually Check?

Never two paths to the same data where one of them writes. The core rule of the borrow checker is that simple.

Rust2 min read
Rust

Before the Rust compiler turns a program into machine code, it checks how long every reference lives and how it is used. The part that does this is called the borrow checker.

One Rule, Two Shapes

At any moment a value can have either any number of shared references (&T) or exactly one mutable reference (&mut T). Never both.

main.rsRust
fn main() { let mut v = vec![1, 2, 3]; let first = &v[0]; // shared borrow v.push(4); // mutable borrow println!("{first}");}

This does not compile. v.push(4) may reallocate the vector, which would leave first pointing at freed memory. The compiler catches it at compile time instead of at run time:

compiler output
error[E0502]: cannot borrow `v` as mutable because it is also borrowed as immutable

Where Does a Lifetime End?

The compiler counts a reference as alive until its last use, not until the end of its scope. This is called non-lexical lifetimes (NLL). Move the println! above the push call and the code compiles, because first is no longer used during push.

main.rsRust
let mut v = vec![1, 2, 3];let first = &v[0];println!("{first}"); // last use of firstv.push(4); // fine now

How It Works Inside the Compiler

The check does not run on source code but on MIR, a simpler intermediate representation. Roughly, there are three steps:

  1. Compute at which points each reference is live.
  2. Find which borrows are active at each point.
  3. Report every access that conflicts with an active borrow.

These rules cost nothing at run time. The whole check finishes during compilation and leaves no trace in the generated machine code.

Sources

  1. Steve Klabnik, Carol Nichols. The Rust Programming Language, “References and Borrowing”. doc.rust-lang.org
  2. Rust Error Codes Index, E0502.
  3. RFC 2094, “Non-lexical lifetimes”. rust-lang.github.io/rfcs
  4. Rust Compiler Development Guide, “MIR borrow check”. rustc-dev-guide.rust-lang.org