Skip to content
Tutorials Center
My learning

Topics

Lesson 27 of 132 ยท Ownership and Borrowing

The Borrow Checker in Practice

Learn how the Rust borrow checker works: non-lexical lifetimes, two-phase borrows, reborrowing, split borrows, and a toolbox of fixes for E0499, E0502, E0506.

You now know the rule: many readers or one writer. In small examples it feels obvious. In real programs it is the part of Rust that makes beginners say "the compiler is fighting me". It is not fighting you; it is following a precise algorithm, and once you know that algorithm, most errors turn into a five-second fix.

This lesson explains what the borrow checker actually measures (hint: not curly braces), why some code that looks wrong compiles, which code that looks fine does not, and a toolbox of fixes you can reach for. It builds on References and Borrowing and prepares you for Lifetimes.

A borrow lasts until its last use

Before Rust 2018 a borrow lasted until the end of the block where the reference variable lived, which forced awkward extra braces. Modern Rust uses non-lexical lifetimes (NLL): a borrow is alive only from where it is created to the last place the reference is used. After that point it is dead, even though the variable is still in scope.

Rust A borrow ends at its last use

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

first is still in scope on the push line, but nothing reads it afterwards, so the shared borrow is over and the mutable borrow needed by push is allowed. Move the println!("first = {first}") below the push and you get E0502 instead:

Rust The same code with the use moved (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

TEXT
error[E0502]: cannot borrow `names` as mutable because it is also borrowed as immutable
 --> main.rs:5:5
  |
4 |     let first = &names[0];
  |                  ----- immutable borrow occurs here
5 |     names.push(String::from("Linus"));
  |     ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ mutable borrow occurs here
6 |     println!("first = {first}");
  |                        ----- immutable borrow later used here

The compiler draws a line from where the borrow starts to the last use; any conflicting access on that line is an error. This mental model, "a borrow is a stretch of the program, from creation to last use", is the key to everything below.

When you read a borrow error, find the third label first: "borrow later used here". The fix is almost always to shorten that stretch (use the reference earlier) or to avoid needing the reference at all (copy or restructure).

Control flow counts

NLL looks at paths through the code, not at the text. A borrow is alive at a point if some path from there can still use it:

Rust Borrows and branches

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

In the else branch the reference is dead, so the push compiles. A loop that carries a reference from one iteration to the next keeps it alive across the whole loop, which is why mutating a collection inside a for over that same collection is rejected.

Why you cannot change a collection while looping over it

for item in &list borrows list for the entire loop, because the iterator is used again at every step:

Rust Mutating while iterating (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

TEXT
error[E0502]: cannot borrow `list` as mutable because it is also borrowed as immutable
 --> main.rs:6:13
  |
4 |       for item in &list {
  |       -           -----
  |       |           |
  |       |           immutable borrow occurs here
  |  _____|           immutable borrow later used here
5 | |         if *item == 2 {
6 | |             list.push(99);
  | |             ^^^^^^^^^^^^^ mutable borrow occurs here
7 | |         }
8 | |     }
  | |_____- this for loop borrows `list` immutably, preventing mutation within its body
  |
  = help: consider using an index-based loop instead, or collecting modifications into a separate collection

This is the classic "iterator invalidation" bug of C++ and Java, which would crash or silently skip elements there. Rust refuses it. The standard fixes:

Rust Three ways to change a list while looking at it

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Option 3 is the best when it exists: retain, iter_mut, drain, dedup and friends do the dangerous work inside the standard library, where the borrow is managed for you.

Two-phase borrows

Here is a line that looks impossible: v.push(v.len()). The method push takes &mut self, and v.len() needs &self to the same vector, so we have a mutable and a shared borrow of v in one expression. It compiles anyway:

Rust v.push(v.len()) works

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

The reason is two-phase borrows. When Rust evaluates v.push(...) it first creates the &mut v in a reserved state, which acts like a shared borrow: it allows reading. Only when the call actually happens (after the arguments are computed) does the borrow become active and exclusive. So the arguments may read v, but they may not change it, and they may not keep a reference that outlives the call.

Two-phase borrows apply to autoref'd method calls and to compound assignment operators such as +=. They do not apply to an explicit let r = &mut v; that you hold on to.

Reborrowing

When you pass a &mut T variable to a function, you might expect it to be moved, since &mut references are not Copy. But this works:

Rust Passing a &mut twice

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

The compiler inserts a reborrow: bump(&mut *handle). You temporarily lend out the thing handle points to; when the call returns, the short-lived reborrow ends and handle is usable again. You can write reborrows by hand too:

Rust
let handle = &mut count;
let short = &mut *handle; // reborrow: handle is frozen while `short` is alive
*short += 1;
*handle += 1;             // fine, `short` is no longer used

Reborrowing is why &mut parameters rarely need annotations, and it explains messages such as "first borrow later used here" that point into a function call: a reborrow of a reborrow is still a borrow of the original.

The toolbox of fixes

Most borrow errors fall into a few shapes. Learn these remedies and you can fix 90% of them mechanically.

Fix 1: copy a small value out

If the thing you need is Copy (numbers, char, bool, shared references), copy it instead of holding a reference:

Rust Copy it out

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Fix 2: clone, knowingly

When you need an owned value and cannot restructure, .clone() ends the borrow:

Rust Clone to end a borrow

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Cloning costs an allocation and a copy of the data. In a cold path that is fine. In a hot loop, prefer a restructure. Never sprinkle .clone() blindly just to silence the compiler: it can hide a real design problem, and on big structures it is slow. Copy, Clone and Move Semantics discusses when it is the right tool.

Fix 3: shorten the borrow

Do the reading in a smaller block, store the result (not the reference), then mutate:

Rust Compute first, mutate after

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Fix 4: use an index instead of a reference

A reference into a Vec is invalidated by pushes. An index is just a number and stays valid as long as the item is not removed. This is the standard trick for graphs, trees stored in a Vec, and entity lists in games:

Rust Indices instead of references

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Fix 5: split a borrow

The borrow checker tracks fields separately, so two &mut to two different fields of a struct are fine:

Rust Disjoint fields can be borrowed together

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

That works only when the borrow checker can see the fields, that is, in direct field access. If the borrows go through methods like p.name_mut() and p.score_mut(), each method borrows the whole Player, and you get E0499. For slices, split_at_mut and split_first_mut hand out two non-overlapping &mut pieces safely, and iter_mut hands out one &mut per element:

Rust split_at_mut: two non-overlapping &mut

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

The compiler cannot prove that data[0] and data[3] are different places, since indices are runtime values, so &mut data[0] together with &mut data[3] is an error. split_at_mut is implemented with a little unsafe inside the standard library and exposes a safe API that guarantees the halves never overlap.

Fix 6: change who owns what

Sometimes the error is telling you that the design has two owners fighting for one value. Options: move the data into a method (impl on the struct that owns it), pass only the pieces a function needs rather than the whole struct, or, as a last resort, use runtime-checked sharing such as RefCell (see Cell and RefCell).

E0506: assigning to a borrowed value

A cousin of E0502: you cannot assign to a variable while a reference to it is still going to be used.

Rust Assigning while borrowed (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

TEXT
error[E0506]: cannot assign to `level` because it is borrowed
 --> main.rs:5:5
  |
3 |     let view = &level;
  |                ------ `level` is borrowed here
4 |
5 |     level = 4;
  |     ^^^^^^^^^ `level` is assigned to here but it was already borrowed
6 |
7 |     println!("view = {view}");
  |                       ---- borrow later used here

The fix is the usual one: finish with view first, or copy the number (let view = level;).

What NLL still cannot do

The borrow checker is conservative: it rejects every program it cannot prove safe, so some safe programs are rejected too. The best-known case is returning a reference from one branch of a conditional borrow (the "Problem case #3"), for example looking something up in a map and inserting if it is missing. It is solved in practice by structuring the code with APIs such as the entry method, or with a second lookup:

Rust Lookup or insert without fighting the checker

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

When you hit such a wall, do not fight it with unsafe. Reshape the code; there is nearly always a clean version, and the standard library APIs were designed to provide it.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. With non-lexical lifetimes, how long does a shared borrow stored in a local variable last?

    NLL ends a borrow at the last point where the reference might still be used, even if the variable is still in scope.
  2. 2. Why does v.push(v.len()) compile?

    Two-phase borrows let the argument expressions read the vector before the exclusive borrow becomes active.
  3. 3. Which is the best fix for 'I want to remove some items from a Vec while checking each one'?

    retain does the removal inside the standard library without any outstanding borrow in your code.
  4. 4. Which pair of borrows does the compiler accept?

    Disjoint struct fields are tracked separately. Indexing and method calls borrow the whole value, so the other options conflict.
  5. 5. Why do you not need to write bump(&mut *handle) when calling bump(handle) twice with a handle: &mut u32?

    When a &mut is passed where a &mut is expected, Rust implicitly reborrows it for the duration of the call, so the original is usable again afterwards.

Summary

  • A borrow lasts from its creation to its last use (NLL), not to the end of the block. Conflicts exist only inside that stretch.
  • Read errors from the bottom label up: "borrow later used here" shows what to shorten.
  • You cannot mutate a collection while iterating over it; use retain, iter_mut, collect-then-apply, or indices.
  • Two-phase borrows allow v.push(v.len()); implicit reborrows let you pass a &mut more than once.
  • Fix toolbox: copy small values, clone knowingly, shorten the borrow, use indices instead of references, split borrows (fields, split_at_mut), or restructure ownership.
  • The checker is conservative. Reshape code with APIs like entry rather than reaching for unsafe.

Next: Slices