valfz

What the borrow checker is actually checking

A working model of Rust borrowing: where a borrow is live, what it covers, and what a signature promises, with real compiler output for each case.

topic
rust
date
read
17 min

The borrow checker enforces three rules, and each one fits in a sentence. What takes longer to learn is the information it applies them to: the stretch of code over which a borrow is in use, the part of a value the borrow covers, and the signature of every function being called. With those in mind, most borrow errors can be predicted before compiling, and the ones that still appear point at a specific fix.

Every program below was compiled with rustc 1.99.1 in a fresh cargo new project (edition 2024). The diagnostics are pasted from that compiler.

Three rules

  • A value has exactly one owner. Assigning it or passing it by value moves it, and the old name can no longer be used (error E0382).
  • At any point in the program, a value can have any number of shared references (&T) or one exclusive reference (&mut T), never both at once (E0502, E0499).
  • A reference cannot outlive the value it points to (E0597).

The rules talk about points in the program, so everything depends on how the compiler decides which borrows exist at a given point. The rest of this article is about that decision.

A borrow lasts until its last use

src/main.rs
fn main() {
    let mut scores = vec![10, 20, 30];
    let first = &scores[0];
    scores.push(40);
    println!("first = {first}");
}
error[E0502]: cannot borrow `scores` as mutable because it is also borrowed as immutable
 --> src/main.rs:4:5
  |
3 |     let first = &scores[0];
  |                  ------ immutable borrow occurs here
4 |     scores.push(40);
  |     ^^^^^^^^^^^^^^^ mutable borrow occurs here
5 |     println!("first = {first}");
  |                        ----- immutable borrow later used here

For more information about this error, try `rustc --explain E0502`.
error: could not compile `borrows` (bin "borrows") due to 1 previous error

Later listings cut those two closing lines.

first points into the vector’s heap buffer, and push needs &mut scores. The second rule forbids that combination for a concrete reason: push may have to move the elements to a larger buffer, which would leave first pointing at freed memory. Printing capacity() and as_ptr() around this particular push on the test machine showed the capacity going from 3 to 6 and the buffer address changing.

The diagnostic has three labels: where the first borrow starts, where the conflicting borrow happens, and where the first borrow is used afterwards. Read the third one first. Move the println! above the push and the program compiles:

src/main.rs
fn main() {
    let mut scores = vec![10, 20, 30];
    let first = &scores[0];
    println!("first = {first}");
    scores.push(40);
    println!("{scores:?}");
}
first = 10
[10, 20, 30, 40]

first is still in scope when push runs, but the borrow it holds has ended. A borrow is live from the point where it is created to the last point where the reference, or anything derived from it, may still be used. The compiler computes that span over the control-flow graph of the function, an analysis known as non-lexical lifetimes. When an error message says “lifetime”, read it as this span of code.

Scope comes back in for types that implement Drop. Dropping is a use, and it happens at the end of the scope, so a MutexGuard keeps its borrow of the mutex alive until the closing brace even when no later line mentions it. rustc reports that case as a borrow that “might be used here, when guard is dropped”. Calling drop(guard) earlier ends the borrow at that line.

Method calls borrow in two phases

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

This compiles and prints [1, 2, 3, 3], which the rules as stated do not explain. The call means Vec::push(&mut v, v.len()), and the receiver is evaluated before the argument, so an exclusive borrow of v already exists when v.len() asks for a shared one. Written in that explicit form, the same call is rejected:

src/main.rs
fn main() {
    let mut v = vec![1, 2, 3];
    Vec::push(&mut v, v.len());
    println!("{v:?}");
}
error[E0502]: cannot borrow `v` as immutable because it is also borrowed as mutable
 --> src/main.rs:3:23
  |
3 |     Vec::push(&mut v, v.len());
  |     --------- ------  ^ immutable borrow occurs here
  |     |         |
  |     |         mutable borrow occurs here
  |     mutable borrow later used by call
...

The method-call form is accepted because the &mut v that the compiler inserts for the receiver is a two-phase borrow. It starts out reserved, and in that state it behaves like a shared borrow. It becomes exclusive when it is first used, which is the moment push is called. Between those two points other code may read v. Writing is still refused:

src/main.rs
fn main() {
    let mut v = vec![1, 2, 3];
    v.push(v.pop().unwrap());
    println!("{v:?}");
}
error[E0499]: cannot borrow `v` as mutable more than once at a time
 --> src/main.rs:3:12
  |
3 |     v.push(v.pop().unwrap());
  |     - ---- ^ second mutable borrow occurs here
  |     | |
  |     | first borrow later used by call
  |     first mutable borrow occurs here
...

The compiler guide lists where two-phase borrows apply: the automatic &mut on a method receiver, mutable reborrows in function arguments, and the implicit borrow in an overloaded compound assignment such as +=. An &mut written out by hand is never two-phase, which is why the explicit call failed. For the pop case, evaluate the argument first: let last = v.pop().unwrap(); v.push(last);.

A borrow covers a path, and a method call covers all of self

src/main.rs
struct Parser {
    input: String,
    errors: Vec<String>,
}

impl Parser {
    fn report(&mut self, message: &str) {
        self.errors.push(message.to_string());
    }
}

fn main() {
    let mut parser = Parser {
        input: String::from("let x = ;"),
        errors: Vec::new(),
    };

    let input = &parser.input;
    parser.report("expected expression");
    println!("{input}: {:?}", parser.errors);
}
error[E0502]: cannot borrow `parser` as mutable because it is also borrowed as immutable
  --> src/main.rs:19:5
   |
18 |     let input = &parser.input;
   |                 ------------- immutable borrow occurs here
19 |     parser.report("expected expression");
   |     ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ mutable borrow occurs here
20 |     println!("{input}: {:?}", parser.errors);
   |                ----- immutable borrow later used here
...

Replace the method call with the statement from its body and the conflict disappears:

src/main.rs
    let input = &parser.input;
    parser.errors.push("expected expression".to_string());
    println!("{input}: {:?}", parser.errors);
let x = ;: ["expected expression"]

Inside one function body, the checker tracks borrows per path. parser.input and parser.errors are different places, so a shared borrow of one and an exclusive borrow of the other do not overlap.

The call parser.report(..) means Parser::report(&mut parser, ..). The signature asks for &mut self, which is exclusive access to the whole struct, input included. The checker never looks inside report to find out that only errors is touched. Each function body is checked on its own, against the signatures of the functions it calls. That boundary is deliberate: if callers were checked against bodies, an edit inside a private method could break code in another crate.

Getters have the same effect. With fn input(&self) -> &str defined on Parser, writing let input = parser.input(); in the working version brings E0502 back at the push, because the returned &str keeps all of parser borrowed for as long as it is used.

What a lifetime annotation promises

Since callers are checked against signatures alone, a signature has to say which borrows a returned reference depends on. Lifetime parameters carry that information.

src/main.rs
fn longest<'a>(a: &'a str, b: &'a str) -> &'a str {
    if a.len() >= b.len() { a } else { b }
}

fn main() {
    let title = String::from("borrowing");
    let result;
    {
        let other = String::from("owning");
        result = longest(&title, &other);
    }
    println!("{result}");
}
error[E0597]: `other` does not live long enough
  --> src/main.rs:10:34
   |
 9 |         let other = String::from("owning");
   |             ----- binding `other` declared here
10 |         result = longest(&title, &other);
   |                                  ^^^^^^ borrowed value does not live long enough
11 |     }
   |     - `other` dropped here while still borrowed
12 |     println!("{result}");
   |                ------ borrow later used here
...

Using 'a on both parameters and on the return type tells the caller that the result may point into either argument, so both must stay borrowed for as long as the result is used. On this input longest would return title, which is still alive at the println!. The checker holds the caller to the signature without evaluating the function.

A signature that ties the result to one input makes a narrower promise:

src/main.rs
fn first_word<'a>(text: &'a str, separator: &str) -> &'a str {
    text.split(separator).next().unwrap_or(text)
}

fn main() {
    let title = String::from("borrowing, briefly");
    let result;
    {
        let separator = String::from(",");
        result = first_word(&title, &separator);
    }
    println!("{result}");
}

This prints borrowing. The result depends on text only, so separator may be dropped while result is still in use. The function body is held to the same contract. Change the fallback so that it could return the separator:

src/main.rs
fn first_word<'a>(text: &'a str, separator: &str) -> &'a str {
    text.split(separator).next().unwrap_or(separator)
}
error[E0621]: explicit lifetime required in the type of `separator`
 --> src/main.rs:2:5
  |
2 |     text.split(separator).next().unwrap_or(separator)
  |     ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ lifetime `'a` required
...

An annotation records a relationship between borrows and leaves the lifetimes of the values themselves untouched. The compiler checks the relationship from both sides: the body must uphold it, and every caller must respect it. When annotations are left out, the elision rules fill them in, and for a method they tie the result to self. That is the rule behind the getter example above.

A correct program the checker rejects

The analysis is conservative, and one well-known pattern shows where:

src/main.rs
use std::collections::HashMap;

fn get_or_insert<'m>(map: &'m mut HashMap<u32, String>, key: u32) -> &'m String {
    if let Some(value) = map.get(&key) {
        return value;
    }
    map.insert(key, String::from("default"));
    &map[&key]
}
error[E0502]: cannot borrow `*map` as mutable because it is also borrowed as immutable
 --> src/main.rs:7:5
  |
3 | fn get_or_insert<'m>(map: &'m mut HashMap<u32, String>, key: u32) -> &'m String {
  |                  -- lifetime `'m` defined here
4 |     if let Some(value) = map.get(&key) {
  |                          --- immutable borrow occurs here
5 |         return value;
  |                ----- returning this value requires that `*map` is borrowed for `'m`
6 |     }
7 |     map.insert(key, String::from("default"));
  |     ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ mutable borrow occurs here
...

No execution reaches insert while the borrow from get is in use: either the function has already returned, or get produced None. But the returned borrow has to last for 'm, which extends past the end of the function, and rustc 1.99.1 applies that requirement to the borrow on every path, including the one that falls through. The NLL RFC calls this problem case #3.

This behavior is version-specific. The Rust blog announced in August 2026 that nightly builds enable the next iteration of the borrow checker, Polonius Alpha, whose analysis of this requirement follows control flow. The nightly installed next to the stable toolchain used here (1.100.0-nightly, 2026-08-21) compiles this function unchanged. On 1.99.1, do the lookup and the insertion under one borrow with map.entry(key).or_insert_with(|| String::from("default")).

Fixes, in order of preference

Shrink the borrow first. Move the last use above the mutation, as in the second listing. Copy the value out when the type is Copy: let first = scores[0]; holds an i32 and no borrow. Compute arguments into locals before a call. These changes cost nothing at run time, and they tend to make it clearer what the code needs and when.

If the borrow cannot be shortened, restructure ownership so that the borrow covers less. A method that needs one part of a struct can live on that part:

src/main.rs
struct Diagnostics {
    errors: Vec<String>,
}

impl Diagnostics {
    fn report(&mut self, message: &str) {
        self.errors.push(message.to_string());
    }
}

struct Parser {
    input: String,
    diagnostics: Diagnostics,
}

fn main() {
    let mut parser = Parser {
        input: String::from("let x = ;"),
        diagnostics: Diagnostics { errors: Vec::new() },
    };

    let input = &parser.input;
    parser.diagnostics.report("expected expression");
    println!("{input}: {:?}", parser.diagnostics.errors);
}

This compiles and prints the same line as the field-access version, because parser.diagnostics.report(..) borrows one field. Storing an index or a key where a long-lived reference would otherwise sit belongs to the same group, with a caveat: the compiler does not track an index, so it can outlive the element it referred to and then select the wrong one or panic. The cost of restructuring is design work, and sometimes a wider API.

Clone when both of those would distort the design. let input = parser.input.clone(); ends the conflict by creating a second value with its own owner. The price is an allocation and a copy, and the copy will not see later changes to the original. rustc states the trade itself when it suggests this fix for a moved value: “consider cloning the value if the performance cost is acceptable”.

Rc<RefCell<T>> comes last because it moves the second rule from compile time to run time:

src/main.rs
use std::cell::RefCell;

fn main() {
    let scores = RefCell::new(vec![10, 20, 30]);
    let all = scores.borrow();
    scores.borrow_mut().push(40);
    println!("first = {}", all[0]);
}
thread 'main' (1233326) panicked at src/main.rs:6:12:
RefCell already borrowed
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace

This is the conflict from the first listing, accepted by the compiler and found only when the offending line runs. RefCell keeps a borrow counter that is checked on every borrow and borrow_mut. Rc adds a reference count and cannot be moved to another thread (rustc rejects the attempt with E0277). Values that point at each other through Rc in a cycle are never freed. These types exist for data that has no single owner, such as a graph or a set of callbacks sharing state. Used to silence a borrow error in code that does have a clear owner, they turn a compile error into a possible panic.

keyboard

h
home
w c a
writing, courses, about
n p
next and previous lesson
j k
scroll down and up
g G
top and bottom of the page
t
switch light and dark
?
this help

shortcuts are