CodeBlanks Logo Icon CodeBlanks

Borrow checker

Learn how the borrow checker runs on MIR.

The borrow checker

The borrow checker runs on MIR and checks three things: that no reference outlives the value it points to (lifetimes), that there's no overlapping &mut access at the same time, and that no moved or uninitialized value is used. In some cases there are refinements that fit the rules to how code is written; for example two-phase borrows:

let mut v = vec![1, 2];
v.push(v.len());   // &mut v is taken, but it "activates" after the argument is computed

Without this, the &v needed for v.len() would clash with push's &mut v.

Polonius

There are some programs the current checker rejects that are actually safe. The best known is the pattern that returns what it found in a map and inserts when it doesn't find it. The next-generation checker Polonius is designed to accept these cases; until it arrives, the entry API or a two-step lookup is used:

// today's solution: a single lookup with entry
let deger = harita.entry(anahtar).or_insert_with(|| hesapla());

Practice Two-phase borrow

For let mut v = vec![1, 2];, run v.push(v.len()); and print the vector with {:?}.

Starter code

main.rs
fn main() {
    // buraya yaz
}

Sample solution

main.rs
fn main() {
    let mut v = vec![1, 2];
    v.push(v.len());
    println!("{:?}", v);
}

Expected output

[1, 2, 2]

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 When the borrow checker finds an error, what's the effect on the program's runtime?

  • Memory grows
  • None; all checking is at compile time, with no runtime cost Correct answer
  • The program slows down
  • Runtime checks are added

Explanation: Borrow checking is a fully static analysis; runtime checking like RefCell exists only when explicitly chosen.

2 Two-phase borrow

Question
let mut v = vec![1, 2];
v.push(v.____());   // [1, 2, 2]
Answer
let mut v = vec![1, 2];
v.push(v.len());   // [1, 2, 2]

Explanation: The argument is computed first; the &mut borrow activates afterwards.

3 Check and error code

Term Meaning
Use of a moved value E0382
Overlapping &mut E0499
Okurken yazma E0502
Short-lived value E0597

All lessons in Expert