$ rustc --explain E0499 # who owns this?

Borrow Checker (Rust VS the World)

// no garbage collector, no dangling pointers

What a borrow checker is

Definition

The borrow checker is the part of the Rust compiler that verifies that references do not outlive the data they point to and that accesses do not conflict while a borrow is live. Together with ownership and Rust's type system, it makes safe Rust memory-safe without requiring a garbage collector. Interior-mutability types such as Cell, RefCell, atomics, and mutexes enforce controlled mutation through a shared reference.
See: The Rust Programming Language, References and Borrowing.

Four bugs it prevents

Classic memory-safety failures of C and C++. Each card shows a program with the bug, the rule it breaks, and the error rustc reports instead of compiling it. These guarantees apply to safe Rust; unsafe code must uphold the same invariants manually.

Use after move

rule broken: one owner per value

let s = String::from("hello");
let t = s;           // ownership moves to t
println!("{s} {t}"); // s is no longer valid

error[E0382]: borrow of moved value: `s`

Without the check: s and t would both free the same buffer: a double free.

Dangling reference

rule broken: no reference outlives its data

let r;
{
    let x = 5;
    r = &x;
}                    // x's storage is no longer valid
println!("{r}");     // r would be dangling

error[E0597]: `x` does not live long enough

Without the check: r would read storage whose lifetime had already ended.

Iterator invalidation

rule broken: one writer or many readers

let mut v = vec![1, 2, 3];
let first = &v[0];   // first points into v's buffer
v.push(4);           // may reallocate and move the buffer
println!("{first}"); // could then point at the old buffer

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

Without the check: if push reallocated, first could read the old buffer after it was freed.

Data race

rule broken: one writer or many readers

let mut hits = 0;
std::thread::scope(|s| {
    s.spawn(|| hits += 1);
    s.spawn(|| hits += 1); // two threads, one counter
});

error[E0499]: cannot borrow `hits` as mutable more than once at a time

Without the check: the concurrent non-atomic writes would be a data race, which is undefined behavior.

How it decides: read, write, own

A useful teaching model tracks what v is allowed to do at each line. Borrowing v removes permissions until the reference's last possible use on that path. Rustc's implementation uses MIR regions, loans, and control-flow data rather than literal R/W/O tokens.

Can v.push(4) run? Same four lines, with lines 3 and 4 swapped.

Can v.push(4) run? Permissions on v in two ordersTwo panels with the same four lines, lines 3 and 4 swapped. Line 2 borrows v[0] into first, so v lends its Write and Own permissions to first until first's last use. Left, rejected with E0502: v.push(4) on line 3 needs Write, but first is still used on line 4, so Write is still lent. Right, accepted: first's last use is line 3, v gets Write and Own back, and v.push(4) on line 4 runs.✗ Rejected: error E0502first is still used after the pushlinecodev may1let mut v = vec![1, 2, 3];RWO2let first = &v[0];RWOfirst borrows v:v lends W and O3v.push(4);RWOpush needs W✗ W is lent to first4println!("{first}");RWOlast use of firstRallowedWlent to firstfirst borrows v✓ Acceptedfirst is no longer used at the pushlinecodev may1let mut v = vec![1, 2, 3];RWO2let first = &v[0];RWOfirst borrows v:v lends W and O3println!("{first}");RWOlast use of first:W and O come back4v.push(4);RWOpush needs W✓ v has W againRallowedWlent to firstfirst borrows v
R = read, W = write, O = own (move or free). Model from the Brown University Rust Book.

// rust vs the world

Borrow checkers across languages

How languages without a borrow checker handle the same failure modes. “Invalidated reference / iterator” means using a reference, view, index, or iterator after collection mutation; exact behavior is API-specific.

ApproachLanguagesUse-after-free / double-freeDangling referenceInvalidated reference / iteratorData racePrice
Garbage collectorJava, Go, C#, JavaScript, OCaml✓reachable objects stay alive✓objects live while referenced◐memory-safe; behavior is collection-specific◐races compile; guarantees vary by languageTracing work, pauses, extra memory
Reference countingSwift classes, Objective-C, CPython✓the count keeps objects alive✓the count keeps objects alive◐memory-safe; behavior is collection-specific◐Swift 6 checks; the others generally do notRetain/release traffic; ARC cycles need weak links; CPython also has cyclic GC
Manual + toolsC, C++, Zig—ASan may find it in an executed path—ASan may find it in an executed path—sanitizers or warnings catch some cases—TSan may find it in an executed pathDetection is incomplete; bugs can reach production
Borrow checkingSafe Rust✓ownership checked at compile time✓lifetimes checked at compile time✓aliasing checked at compile time✓aliasing plus `Send` and `Sync`Annotations and some safe programs rejected
✓ prevented in the language's safe subset, ◐ caught at run time or only in some cases, — not prevented. ASan and TSan only find bugs on paths that execute while instrumented.

Languages with a borrow checker or a similar compile-time check, on the same four bugs:

LanguageCalledUse-after-free / double-freeDangling referenceInvalidated reference / iteratorData raceStatus
Rustownership and borrow checker (rustc_borrowck)✓ownership and moves✓lifetimes✓exclusive mutation✓aliasing plus Send, SyncStable NLL; Polonius Alpha is nightly-default
Swiftexclusivity, ownership/lifetime checking, and data isolation✓ARC; consumed noncopyable values are checked✓ARC plus lifetime-checked nonescaping references◐copy-on-write; indices and some accesses can be invalidated✓Swift 6 data isolation; some enforcement is dynamicStable in Swift 6.4
Mojolifetime checking with origins✓x^ ownership transfer is checked✓origins constrain reference lifetimes◐direct List references are tracked; iterator coverage is incomplete—no language-level data-race guarantee1.2.0 (22 October 2026)
HyloLaw of Exclusivity✓consumed bindings checked✓no first-class references✓exclusivityn/aconcurrency semantics are still being designedResearch, pre-release
Australlinearity checker✓linear values used exactly once✓borrows tied to a region✓one &! at a timen/ano threads yetExperimental
Ada SPARKownership policy (GNATprove)✓moved access values become unusable✓ownership rules and proof◐container rules and proof obligations✓statically excluded under Ravenscar or Jorvik restrictionsIndustrial (AdaCore)
Movereference safety (bytecode verifier)✓moves checked✓references never stored✓exclusive &mutn/ano threadsProduction (Sui, Aptos)
C#ref safety✓GC prevents premature reclamation✓GC; ref escape is checked◐collection mutation often throws at run time—races compileStable ref safety; C# 15
Dscope checks + ownership/borrowing (@live)◐@live functions only◐scope checks in @safe code—not generally container-aware—shared races can compileOpt-in `@live`; `scope` escape analysis under `@safe` with `-preview=dip1000`
C++ (Clang)lifetime safety analysis◐warnings catch some cases◐-Wlifetime-safety warnings◐experimental invalidation warnings—TSan may find executed racesExperimental in Clang 23
OxCamlmodes✓GC; unique consumption is checked✓GC; local cannot escape its region◐memory-safe; logical invalidation is API-specific✓contention and portability modesJane Street's OCaml branch
✓ prevented in the language's safe or checked subset, ◐ caught at run time or only in some cases, — not prevented, n/a no implemented shared-memory threading model. Unsafe code and trusted native boundaries are excluded. Status as of 19 November 2026.

How each one is written:

LanguageSyntaxReferences in structsEscape hatch
Rust
&T&mut T'a
Yes, with lifetime parameters ('a)unsafe; RefCell stays safe by checking borrows at run time
Swift
inoutborrowingconsuming~Copyable~EscapableRefMutableRef
Yes, through Ref, MutableRef, and lifetime-dependent types such as SpanUnsafe*Pointer, nonisolated(unsafe)
Mojo
mutvarx^ref [origin]
Yes, through origin parameters (Pointer, Span)UnsafePointer, UnsafeAnyOrigin, UntrackedOrigin
Hylo
letinoutsinkset
No: values are projected, not referencedUnsafe pointer types
Austral
&[T, R]&![T, R]
Only inside the region R that created themUnsafe modules (FFI)
Ada SPARK
access Taccess all Taccess constant TX'Access
Anonymous access types borrow or observe; storage in composites is restrictedSPARK_Mode => Off
Move
&T&mut Thas copy, drop
No: references cannot be storedNo source-level hatch; VM native functions are trusted
C#
refscopedref struct
ref fields only in a ref structunsafe, pointers
D
scopereturn scope@live
Yes; scope references are prevented from escaping@system, @trusted
C++ (Clang)
[[clang::lifetimebound]][[gsl::Owner]][[gsl::Pointer]]
Partly tracked intra-procedurally; annotations improve precisionUnannotated calls and other analysis gaps
OxCaml
@ local@ unique@ once@ portable@ contended
local values cannot escape their region; stack_ requires stack allocationObj.magic

// rustc_borrowck

NLL, today's borrow checker

Definition

NLL (non-lexical lifetimes) has powered Rust's borrow checker since 2018. It infers the control-flow-graph points where a region must be live, subject to use, outlives, and drop constraints. In a straight-line example this often lets a borrow end after the reference's last possible use instead of at the end of its enclosing block.

Where the borrow checker runs in rustc, and its six stepsTop row: source, AST, HIR with type checking, THIR, MIR, then the highlighted borrowck stage, then MIR optimizations and LLVM. Below is a simplified view of borrow checking: renumber regions, type-check MIR to collect outlives constraints, compute liveness, infer regions, compute loans in scope, and check accesses. Polonius Alpha adds localized constraint-graph reachability to improve loan-liveness information while retaining the rest of the MIR borrow checker.sourcemain.rsASTparse, expandHIRresolve, typeckTHIRtyped treeMIRcontrol-flow graphborrowckrustc_borrowckMIR optsinline, simplifyLLVMmachine codeinside borrowck, for each function body1Renumbera fresh variable forevery lifetime2Type-check MIRcollect outlives'a: 'b at point p3Livenessregions of livelocals cover those points4Region inferencesmallest set ofpoints per region5Loans in scopeforward dataflowover the CFG6Check accessesconflicts and movesE0499, E0502, E0382…Polonius Alpha uses localized constraint-graph reachabilityto refine loan liveness inside the existing MIR borrow checkerOne function at a time: a call is checked against the callee's signature, never its body.
Where NLL runs in rustc, and its six steps.

// "neither a borrower nor a lender be"

Polonius, the next borrow checker

Definition

Polonius Alpha is the next iteration of Rust's borrow checker and is the default on nightly. NLL infers where regions must be live; Alpha uses reachability through a localized graph of regions and control-flow points to approximate where each loan may be live. This is more precise for common branch-sensitive cases, but it is not the fully flow-sensitive legacy Polonius analysis.

Two implementations can be selected on nightly: legacy Datalog Polonius (the original flow-sensitive rules, historically too slow for production) and Polonius Alpha (a rustc-native implementation that landed in 2025 and is the stabilization candidate). Neither accepts a strict superset of the other.

NLL problem case #3 under NLL and under PoloniusThe same match twice. Line 1 calls map.get_mut, creating loan L0; line 2, the Some arm, returns value; lines 3 to 6 are the None arm, which calls map.insert on line 4. Left, NLL's region constraints keep L0 live across both arms, so map.insert is error E0499. Right, Polonius Alpha's localized constraint graph does not carry L0 to the insert in the None arm, so the function compiles.NLL (stable)✗ error E0499Asks: where must the relevant regions be live?Its constraints keep L0 live across both match arms.fn get_default<'r>(map: &'r mut HashMap<K, V>, key: K) -> &'r mut V1match map.get_mut(&key) {loan L0 starts2Some(value) => value,return ties it to 'r3None => {4map.insert(key, V::default());✗ *map still borrowed5map.get_mut(&key).unwrap()6}7}loan L0 (map.get_mut) is livePolonius Alpha (nightly)✓ compilesAsks: can L0 reach this point in the constraint graph?It cannot reach the None arm's insert.fn get_default<'r>(map: &'r mut HashMap<K, V>, key: K) -> &'r mut V1match map.get_mut(&key) {loan L0 starts2Some(value) => value,L0 reaches the result3None => {4map.insert(key, V::default());✓ L0 is not live here5map.get_mut(&key).unwrap()6}7}L0 may reach the callerloan L0 (map.get_mut) is live
NLL problem case #3: rejected in a test with stable rustc 1.99.1, accepted by nightly 2026-11-18, where Polonius Alpha is the default. Rust 1.100.0, released 12 November 2026, still uses NLL. Workaround on stable: map.entry(key).or_default().
  1. 2015stable rustcRust 1.0: lexical borrow checker

  2. 2017stable rustcRFC 2094 proposes NLL

  3. Apr 2018poloniusPolonius proposed, in Datalog

  4. Dec 2018stable rustcNLL ships with Rust 2018 (1.31)

  5. 2019stable rustcNLL on the 2015 edition (1.36)

  6. 2022stable rustcOld checker fully removed (1.63)

  7. Oct 2023poloniusA new rustc-based Polonius roadmap is published

  8. Aug 2025poloniusThe implementation later named Polonius Alpha lands

  9. 6 Aug 2026poloniusAlpha becomes the default on nightly

  10. End of 2026plannedAlpha on stable (target)

  11. After AlphaplannedNo concrete schedule for further Polonius feature work

// nll vs polonius

NLL vs Polonius in detail

Loan: the compiler's record of a borrow. A loan is active at a control-flow point while the borrowed reference might still be used there. Conflicting operations are forbidden during that time—for example, mutating a value while an immutable loan is active.
NLL (stable)Polonius Alpha (nightly default)Datalog Polonius (legacy)
Practical differenceTracks where regions must be live; this can keep a loan active across unrelated branchesTracks whether each specific loan can reach each CFG point, accepting more safe branch-sensitive codeTracks which loans each origin contains at every CFG point
QuestionWhere must each region be live?Can this loan reach this CFG point?Which loans can each origin contain here?
Core representationRegions as sets of CFG pointsLocalized (region, point) constraint graph plus NLL dataSets of loans in origins at each point
AlgorithmRegion inference over the CFGConstraint-graph reachability approximates loan livenessFlow-sensitive Datalog rules to a fixpoint
Problem case #3RejectedAcceptedAccepted
Lending iteratorsRejectedAcceptedAccepted
Linked-list cursorRejectedRejectedAccepted
Measured compile timeBaseline2026 sample: +1.4% mean; a large-function outlier reached 2.5×Historically too slow for production
StatusStable since 2018Nightly default; stable targeted end of 2026Nightly flag only
Nightly flag-Zpolonius=off-Zpolonius=next-Zpolonius=legacy
The Alpha timing is a July 2026 measurement over the 20,000 most-downloaded crates, not a guaranteed cost: the mean regression was 1.4%, 95% of crates were below 5%, and one very large function reached about 2.5×. Source: Rust Blog, Enabling Polonius Alpha on nightly.

The same idea on MIR

The loan of let b = &mut *a under NLL and under Polonius AlphaThe same four-block control-flow graph twice. bb0 creates b, issuing loan bw0, and branches to bb1, the if arm that returns b, and bb2, the else arm that borrows a again; both join in bb3, which returns. Left, NLL's constraints keep the loan live in both arms, so bb2's borrow of a is error E0499. Right, Polonius Alpha does not carry the loan into bb2, where b is dead, so the program is accepted.NLL: constraints keep the loan live in both armsbb0b = &mut *aissues loan bw0bb1 (if)_4 = &mut *breturns through bbb2 (else)_4 = &mut *aborrows *a againbb3return &mut *_4the caller gets '1✗bb2 borrows *a while bw0 is in scope: E0499region of bw0 = {bb0[0..=7], bb1[0..=4], bb2[0..=1], bb3[0..=6]}plus end('1): every point, because b is returned on one pathbw0 livePolonius Alpha: the loan is not live in the else armbb0b = &mut *aissues loan bw0bb1 (if)_4 = &mut *breturns through bbb2 (else)_4 = &mut *aborrows *a againbb3return &mut *_4the caller gets '1✓b is dead in bb2, so no live origin holds bw0 therebw0 ∈ 'b at bb0[2]; 'b ⊆ '_4 in bb1 (through _6);'_4 ⊆ '1 in bb3: the loan reaches the caller only via bb1bw0 live
Real MIR blocks and NLL region (-Zdump-mir=nll) for let b = &mut *a; if true { b } else { a }.

Thirteen programs, three verdicts

ProgramWhat it doesNLLAlphaDatalog
Real bugs: every checker must reject them
Use after moveE0382✗✗✗
Dangling referenceE0597✗✗✗
Iterator invalidationE0502✗✗✗
Data raceE0499✗✗✗
Safe, accepted since NLL
Borrow ends after its last possible uselet first = &v[0]; println!(…); v.push(4)✓✓✓
Two-phase borrowv.push(v.len())✓✓✓
Safe, needs Polonius Alpha
A. get_defaultNLL problem case #3✗✓✓
B. reborrowsmallest example✗✓✓
C. first_zero_or_pushsame shape, with a Vec✗✓✓
D. Filter::nextfiltering lending iterator✗✓✓
Safe, accepted only by legacy Datalog in these tests
E. last_mutwalk to the last node✗✗✓
F. find_slotstop at the first node ≥ target✗✗✓
G. conditionaladvance the cursor on a condition✗✗✓
✓ accepted, ✗ rejected although safe, ✗ rejected because of a real bug. NLL: rustc 1.99.1. Alpha (-Zpolonius=next) and Datalog (-Zpolonius=legacy): nightly 2026-11-18.

Try it

borrowck-cases.rs holds programs A to G.

curl -O https://karolinagorna.net/downloads/borrowck-cases.rs
rustc +stable  --edition=2024 --crate-type=lib borrowck-cases.rs                    # NLL: 10 errors
rustc +nightly --edition=2024 --crate-type=lib -Zpolonius=next   borrowck-cases.rs  # Alpha: 4 errors
rustc +nightly --edition=2024 --crate-type=lib -Zpolonius=legacy borrowck-cases.rs  # Datalog: 0 errors

// cargo check --all-answers

Quiz: the borrow checker

A self-check on everything above, from easy to hard. Nothing is saved, so run it as often as you like. Answer with a click, or with the keyboard (1-4 / A-D to answer, arrows to move).

// one writer or many readers

Borrow checking, easy to hard

Ten questions in order of difficulty: what the checker guarantees, the bugs it stops and how it decides, then NLL, two-phase borrows and the case Polonius Alpha accepts. The snippets were checked with NLL in rustc 1.99.1 and with nightly 2026-11-18.

let mut you = Reader::new();
let quiz = &mut you;       // you lend R, W and O
quiz.answer(1..=10);       // last use of quiz
you.celebrate();           // the borrow is over: compiles
3 easy4 medium3 hard Use after moveRead, write, ownNLLTwo-phase borrowsProblem case #3