Borrowing: References in Rust

Borrowing: References in Rust in Rust: A research library holds a manuscript that never leaves the building -- the library owns it, permanently.

The Analogy: The Reading Room

A research library holds a manuscript that never leaves the building -- the library owns it, permanently. What you can do is request it to a desk in the reading room and read it there. And here is the useful part: ten scholars can crowd round the same open page and all read at once. Nothing goes wrong, because reading changes nothing. There is no queue, no ticket, no contention. Ten readers or one, the manuscript says the same thing.

Now suppose one scholar has permission to annotate it in pencil. While that is happening, nobody else may look at it -- not even to read. That is not the librarian being territorial. A half-written annotation is not a fact yet: a second scholar copying a sentence mid-edit would faithfully copy something that was never true, and would have no way to know. So annotation is exclusive by construction. One pencil, zero other readers, and when the pencil goes down everyone can come back.

There is one more rule, and it is the one nobody argues with. Your reading slip is void the moment the manuscript ceases to exist. If the item is deaccessioned, every slip referring to it is waste paper, and the librarian will simply not issue a slip that outlasts the item it names. A slip pointing at nothing is worse than no slip, because it looks valid.

Rust calls the reading slip a shared reference, written &T, and you may hold any number. It calls the pencil a mutable reference, &mut T, and while one exists no other reference of either kind may. The third rule is that no reference may outlive the value it points to. All three are checked by the compiler, at compile time, with no run-time cost -- so "someone read it while it was half-written" (a data race) and "someone read it after it was destroyed" (a use-after-free) are not hazards you test for and hope to catch. They are shapes of program that do not build.


Syntax or Core Structure

Borrowing is two sigils, & and &mut, and one operator, *. That is the whole surface area.

fn main() {
    let mut text = String::from("hello");

    // A shared reference. Read-only, and you may take as many as you like.
    let r1 = &text;
    let r2 = &text;
    println!("r1 = {r1}, r2 = {r2}, len = {}", r1.len());

    // Nothing moved, so the owner is untouched.
    println!("owner still has: {text}");

    // A mutable reference. Exclusive, and the owner must be declared `mut`.
    let m = &mut text;
    m.push_str(", world");
    println!("through m: {m}");

    // Once m is finished with, the owner is readable again.
    println!("owner now: {text}");

    // Functions borrow exactly the same way.
    println!("words = {}", count_words(&text));
    shout(&mut text);
    println!("after shout: {text}");

    // `*` dereferences when you want the value rather than the reference.
    let n = 41;
    let p = &n;
    println!("p = {p}, *p + 1 = {}", *p + 1);
}

fn count_words(s: &str) -> usize {
    s.split_whitespace().count()
}

fn shout(s: &mut String) {
    s.make_ascii_uppercase();
    s.push('!');
}

Output:

r1 = hello, r2 = hello, len = 5
owner still has: hello
through m: hello, world
owner now: hello, world
words = 2
after shout: HELLO, WORLD!
p = 41, *p + 1 = 42

Notice count_words(&text): the parameter is &str but the argument is &String, and it compiles because of deref coercion. That is not a special case for strings -- &Vec<T> becomes &[T] and &Box<T> becomes &T the same way -- and it is why &str is the right parameter type even when every caller you can imagine has a String.

Now the three ways to get it wrong, because these diagnostics are the rules. First, a shared reference that is still needed while the owner is mutated:

fn main() {
    let mut text = String::from("hello");
    let r = &text;
    text.push_str(" world");
    println!("r = {}", r);
}

Output (compile error):

error[E0502]: cannot borrow `text` as mutable because it is also borrowed as immutable
 --> src/main.rs:4:5
  |
3 |     let r = &text;
  |             ----- immutable borrow occurs here
4 |     text.push_str(" world");
  |     ^^^^^^^^^^^^^^^^^^^^^^^ mutable borrow occurs here
5 |     println!("r = {}", r);
  |                        - immutable borrow later used here

Second, two mutable references at once:

fn main() {
    let mut text = String::from("hello");
    let a = &mut text;
    let b = &mut text;
    a.push('!');
    println!("{b}");
}

Output (compile error):

error[E0499]: cannot borrow `text` as mutable more than once at a time
 --> src/main.rs:4:13
  |
3 |     let a = &mut text;
  |             --------- first mutable borrow occurs here
4 |     let b = &mut text;
  |             ^^^^^^^^^ second mutable borrow occurs here
5 |     a.push('!');
  |     - first borrow later used here

Third, a reference that would outlive its value:

fn dangle() -> &String {
    let s = String::from("gone");
    &s
}

Output (compile error, trimmed):

error[E0106]: missing lifetime specifier
 --> src/main.rs:1:16
  |
1 | fn dangle() -> &String {
  |                ^ expected named lifetime parameter
  |
help: this function's return type contains a borrowed value, but there is no
      value for it to be borrowed from

That third one is worth dwelling on, because the obvious fix does not work. Add a lifetime -- fn dangle<'a>() -> &'a String -- and the error simply relocates to error[E0515]: cannot return reference to local variable. There is no way to write this function, and that is deliberate: s is dropped at the closing brace, so any reference to it is a slip for a manuscript that has been shredded. The fix is to return the String itself and hand over ownership.


Technical Depth: The Two Rules, and What They Actually Buy You

The rules, stated precisely

At any point in the program, for any given value, you may have either any number of shared references &T or exactly one mutable reference &mut T -- never both. And no reference may outlive the value it refers to.

That is often taught as "the borrow checker is strict about mutation", which misses the point. The rule forbids aliasing plus mutation, and aliasing plus mutation is the precondition for an entire catalogue of bugs:

Shape the rule forbidsBug it would otherwise be
A & alive while a &mut writesReading a half-updated value; a data race, if the two are on different threads
Two &mut to the same valueLost updates, with no defined ordering between the writers
A reference that outlives its ownerUse-after-free; a pointer that looks valid and is not
A & into a Vec across a pushA dangling pointer, because push may reallocate and move the buffer

The last row is the sharpest illustration. v.push(x) can outgrow the current allocation, allocate a bigger one, copy the elements across, and free the old buffer. Any &v[0] taken beforehand now points into freed memory. This is not a hypothetical -- it is exactly the C++ "iterator invalidation" family, and in Rust it is error[E0502] instead of a crash on a Tuesday.

Borrows end at their last use, not at the closing brace

This is the detail that decides whether Rust feels workable. Since the 2018 edition the borrow checker uses non-lexical lifetimes: a borrow's region ends after its final use, not at the end of the enclosing block. So this compiles:

let mut v = vec![1, 2, 3];
let first = &v[0];
println!("first = {first}");
v.push(4);            // fine: `first` was last used above
println!("{v:?}");

and moving the push one line earlier does not. If you have read older Rust advice about restructuring code into inner blocks to end borrows, that advice is obsolete; write the natural order and the checker follows it.

The two reference types are not symmetrical

TypeIs it Copy?How many at onceCan write through it
&TYesAny numberNo
&mut TNoExactly oneYes

&mut T not being Copy is what enforces exclusivity -- if you could copy it, "exactly one" would be unenforceable. But that raises an obvious question: how can you pass the same &mut to two functions in a row without moving it? The answer is implicit reborrowing. When a &mut T is passed where a &mut T is expected, the compiler inserts &mut *m rather than moving m, so the original is usable again once the callee returns. Similarly, a &mut T coerces to a &T wherever a shared reference is wanted.

Auto-reference at method calls, and coercion at call sites

You almost never write & before a method call, because the compiler inserts it: text.len() becomes str::len(&text) and v.push(x) becomes Vec::push(&mut v, x). That second one is why v must be declared mut -- the &mut you never typed is still a &mut. Deref coercion then handles the other direction at call sites:

  • &String where &str is wanted.
  • &Vec<T> where &[T] is wanted.
  • &mut Vec<T> where &mut [T] is wanted.
  • &Box<T> where &T is wanted.

Taking the coerced-to type in your signatures is free and strictly more general, which is why clippy's ptr_arg lint fires on fn f(s: &String).

Disjoint fields can be borrowed separately

The borrow checker reasons about paths, not whole variables, so two different fields of one struct can be mutably borrowed at the same time:

struct Account {
    owner: String,
    balance: i64,
}

fn describe(a: &Account) -> String {
    format!("{} has {}", a.owner, a.balance)
}

fn deposit(a: &mut Account, amount: i64) {
    a.balance += amount;
}

fn initial(s: &str) -> Option<char> {
    s.chars().next()
}

fn main() {
    let mut acct = Account { owner: String::from("ada"), balance: 100 };

    // Many shared borrows at once.
    let x = &acct;
    let y = &acct;
    println!("{} / {}", describe(x), describe(y));

    // One mutable borrow, created and finished within the call.
    deposit(&mut acct, 50);
    println!("{}", describe(&acct));

    // A &mut is not Copy, but passing it reborrows rather than moving it,
    // so `m` is still usable after each call.
    let m = &mut acct;
    deposit(m, 10);
    deposit(m, 10);
    println!("{}", describe(m));

    // Disjoint field paths can be mutably borrowed simultaneously.
    let name = &mut acct.owner;
    let bal = &mut acct.balance;
    name.push_str(" lovelace");
    *bal *= 2;
    println!("{} / {}", name, bal);

    // Deref coercion: &String is accepted where &str is wanted.
    println!("initial = {:?}", initial(&acct.owner));
}

Output:

ada has 100 / ada has 100
ada has 150
ada has 170
ada lovelace / 340
initial = Some('a')

The two deposit(m, ...) calls are the reborrow rule made visible: if &mut behaved like a normal move, the second call would fail. And the name/bal pair only works because they are different paths. Two methods that each take &mut self cannot be interleaved the same way, however true it is that they touch different fields -- the signature says "all of me". That asymmetry is why the standard library provides split_at_mut and iter_mut: they hand out several disjoint &mut from one &mut self in a way the checker can verify.


Real World Example: Sanitising Records In Place

Cleaning up a batch of rows is the job where borrowing earns its keep. The caller has the data and wants to keep it; the sanitiser needs to change it; and a reader afterwards wants to point into it without copying anything out.

struct Record {
    id: u32,
    email: String,
    score: i32,
}

#[derive(Debug, Default)]
struct Fixes {
    trimmed: usize,
    lowercased: usize,
    clamped: usize,
}

/// Reads only. The caller keeps the data, and the returned reference points
/// straight into it -- nothing is copied.
fn worst(records: &[Record]) -> Option<&Record> {
    records.iter().min_by_key(|r| r.score)
}

/// Writes in place. One `&mut` for the whole pass, and no second Vec.
fn sanitise(records: &mut [Record]) -> Fixes {
    let mut fixes = Fixes::default();

    for r in records.iter_mut() {
        if r.email.trim().len() != r.email.len() {
            let fixed = r.email.trim().to_string();
            r.email = fixed;
            fixes.trimmed += 1;
        }
        if r.email.chars().any(|c| c.is_ascii_uppercase()) {
            r.email.make_ascii_lowercase();
            fixes.lowercased += 1;
        }
        if r.score > 100 {
            r.score = 100;
            fixes.clamped += 1;
        } else if r.score < 0 {
            r.score = 0;
            fixes.clamped += 1;
        }
    }

    fixes
}

fn main() {
    let mut records = vec![
        Record { id: 1, email: String::from("  Ada@Example.COM "), score: 118 },
        Record { id: 2, email: String::from("linus@example.com"), score: 74 },
        Record { id: 3, email: String::from("Grace@Example.com"), score: -5 },
    ];

    let fixes = sanitise(&mut records);
    println!("{fixes:?}");

    for r in &records {
        println!("{} {:<20} {}", r.id, r.email, r.score);
    }

    match worst(&records) {
        Some(r) => println!("worst = id {} at {}", r.id, r.score),
        None => println!("worst = none"),
    }
}

Output:

Fixes { trimmed: 1, lowercased: 2, clamped: 2 }
1 ada@example.com      100
2 linus@example.com    74
3 grace@example.com    0
worst = id 3 at 0

Two signatures, two contracts, and the caller keeps the vector either way. sanitise takes &mut [Record] and rewrites the rows where they sit -- no second Vec is allocated, no Record is cloned, and records is still there afterwards for the loop and for worst to read. Compare that with the reflex of returning a new collection: correct, easy, and it doubles peak memory for a job that changes three fields.

worst is the more interesting half. It returns Option<&Record> -- a reference into the caller's vector -- and lifetime elision quietly ties that reference's lifetime to the input slice, so the compiler knows the result may not outlive records. This is where the borrow rule stops being a restriction and starts being a feature: try holding the result of worst and then calling records.push(...), and you get error[E0502], because push may reallocate the buffer and leave your reference pointing at freed memory. The alternative design -- returning an owned Record -- would be a clone per call, forever, to avoid a bug the compiler can simply prevent.

The ordering in main is not arbitrary and cannot be shuffled, which is exactly the guarantee you want. sanitise(&mut records) needs exclusive access, so it cannot overlap with the printing loop or with worst. Because borrows end at their last use, the exclusive borrow expires the instant sanitise returns, so the code reads top to bottom with no ceremony -- but "render the table while the sanitiser is halfway through row two" is not a race you have to reason about, it is a program that does not compile.

One deliberate choice worth copying: the parameters are &[Record] and &mut [Record], not &Vec<Record> and &mut Vec<Record>. Deref coercion means a Vec caller writes &records and &mut records exactly as they already do, but now an array, a boxed slice, or a sub-slice such as &mut records[1..] works too. Taking the most general reference type costs nothing at the call site and widens what the function accepts, which is precisely what clippy's ptr_arg lint is nudging you towards.


Common Mistakes

  1. Mutating the owner while a shared reference is still needed. let r = &v; v.push(1); println!("{r:?}"); is error[E0502]. Read the third underline -- "immutable borrow later used here" -- because that is the line you can usually move, and moving it is the whole fix.
  1. Two mutable references at once. error[E0499]. If the two really do touch different parts of the data, say so with paths (&mut s.a and &mut s.b) or with split_at_mut, rather than reaching for RefCell.
  1. Forgetting mut on the owner. let s = String::new(); let r = &mut s; gives error[E0596]: cannot borrow s as mutable, as it is not declared as mutable. The mutability lives on the binding, not on the reference type alone.
  1. Trying to write through a shared reference. let r = &n; *r = 5; gives error[E0594]: cannot assign to *r, which is behind a & reference. &T is a reading slip; there is no version of it that writes.
  1. Returning a reference to a local. E0106 first, then E0515 if you add a lifetime. Every attempt fails, because none of them can make the local outlive the function. Return the owned value.
  1. Holding a reference into a Vec across a resize. push, insert, extend, reserve, and remove can all move the buffer. Take the index instead of the reference if you need to survive a resize.
  1. Writing &String or &Vec<T> parameters. It compiles, and it turns away every caller holding a &str, a literal, an array, or a sub-slice. Use &str and &[T]; clippy's ptr_arg will remind you.
  1. Forgetting the * when comparing or assigning through a reference. if r == 5 where r: &i32 fails, because &i32 and i32 are different types. Write *r == 5, or r == &5 if that reads better.
  1. Restructuring code into inner blocks to end a borrow. That was necessary before the 2018 edition. Today borrows end at their last use, so the extra braces are noise -- write the straightforward order and only investigate if the checker actually objects.

Best Practices

  • Default to &T in parameters, upgrade to &mut T when the function must change something, and take by value only when it must keep or consume it. Signatures in that order are self-documenting.
  • Prefer the coerced-to types: &str over &String, &[T] over &Vec<T>, &mut [T] over &mut Vec<T>. Reserve &Vec<T> for the rare function that genuinely needs capacity or reserve.
  • Return owned values from public functions unless handing back a reference is the point. A returned reference imports the caller's lifetime questions into your API.
  • When E0502 fires, look for a line to move before looking for something to clone. The borrow usually ends one line later than it needs to.
  • Borrow disjoint fields by path when you need two mutable views of one struct, and use split_at_mut or iter_mut for slices. Reach for RefCell only when the sharing pattern genuinely cannot be expressed statically.
  • Keep mutable borrows short. A &mut that spans forty lines is a lock held for forty lines, and it will eventually collide with something you want to read.
  • Store indices rather than references when the collection may be resized between uses. An index survives a reallocation; a reference does not, and the compiler will make you prove you knew that.
  • Let the compiler insert & and &mut at method calls, but remember it is doing so. When v.push(x) demands mut v, that is the invisible &mut talking.

Practice Exercises

  1. Provoke all four errors. Write one small program per diagnostic and record the exact code and message for E0502, E0499, E0596, and E0594. For each, write the smallest fix that keeps the intent -- not the fix that deletes the feature.
  1. Count without copying. Write fn stats(samples: &[f64]) -> (f64, f64, f64) returning min, max, and mean in a single pass, then fn normalise(samples: &mut [f64]) that rescales every value into 0.0 to 1.0 in place. Call stats before and after and confirm the second call reports 0.0, 1.0, and something between.
  1. Make the dangling reference impossible. Start from fn longest_word(text: &str) -> &str and get it compiling with no explicit lifetime annotations. Then try to write a version that builds a String inside the function and returns a slice of it, read the error, and explain in one sentence why elision cannot save you.
  1. Break the sanitiser deliberately. In the Record example, try each of these and note the error code: calling worst(&records) first and printing the result after sanitise(&mut records); pushing a fourth record while holding the result of worst; changing sanitise to take &[Record]; and taking &mut r.email and &mut r.score at the same time inside the loop (this one should work -- explain why).