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.
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:
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.
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:
- Compute at which points each reference is live.
- Find which borrows are active at each point.
- 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
- Steve Klabnik, Carol Nichols. The Rust Programming Language, “References and Borrowing”. doc.rust-lang.org
- Rust Error Codes Index, E0502.
- RFC 2094, “Non-lexical lifetimes”. rust-lang.github.io/rfcs
- Rust Compiler Development Guide, “MIR borrow check”. rustc-dev-guide.rust-lang.org