Rust Reference ยท Concepts
Borrowing rules in Rust
Reference for Rust's borrowing rules: many shared references or one exclusive reference, non-lexical lifetimes, reborrows, two-phase borrows and common errors.
Borrowing lets code use a value without taking ownership of it. You create a reference with &value (a shared borrow) or &mut value (an exclusive borrow). The borrow checker enforces one rule at every point in the program: at any moment you may have either any number of shared references or exactly one exclusive reference to a place, never both, and every reference must be valid for as long as it is used.
This is "aliasing XOR mutability". It rules out data races, iterator invalidation and use-after-free in safe code, and it lets the compiler assume that a &mut reference is the only way to reach its data, which enables optimizations.
let mut v = vec![1, 2, 3]; let first = &v[0]; // shared borrow starts // v.push(4); // error[E0502]: needs an exclusive borrow while `first` is live println!("{first}");
Try 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.
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.
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 rules in detail
Exclusive means alone
While a &mut T is live, nothing else may read or write the same place, directly or through another reference. The compiler error codes tell you which rule fired: E0502 (a shared and an exclusive borrow overlap), E0499 (two exclusive borrows overlap), E0506 (assigning to a borrowed value) and E0505 (moving a borrowed value).
Non-lexical lifetimes
A borrow lasts from where it is created to its last use, not to the end of the enclosing block. In the first example, a and b are last used in the println!, so double_all(&mut nums) is legal even though the variables are still in scope. This analysis is called non-lexical lifetimes (NLL).
Reborrowing
Passing a &mut T variable to a function that wants &mut T does not move it. The compiler inserts a reborrow (&mut *r), a shorter-lived exclusive borrow, and the original becomes usable again afterwards. You can also reborrow a shared view out of an exclusive one with &*r, but the exclusive reference is then frozen until the shared view's last use.
Two-phase borrows
In v.push(v.len()), the compiler first creates a reserved &mut v for the call, evaluates the arguments (which may read v), and activates the exclusive borrow only for the call itself. That is why this code compiles even though it looks like an overlap.
Usage notes
- References never outlive their referent. The check is about lifetimes, not just overlap.
- Borrowing a field borrows only that field when you write the field path directly. Going through a method (
p.score_mut()) borrows the whole struct, which is why getters can block other borrows. - Iteration borrows the collection. Pushing into a
Vecwhile afor x in &vloop runs is an error; collect indexes first, or iterate over a clone, or build a new vector. - Prefer
&strand&[T]parameters over&Stringand&Vec<T>; they accept more callers. - When the rules are too strict, use indexes, split the borrow, restructure ownership, or use interior mutability, which moves the check to run time.
&mutis not "mutable reference" in the sense of the variable.let mut r = &x;lets you re-pointr;let r = &mut x;lets you changexthroughr.- Raw pointers do not follow the borrow rules, but using them incorrectly is undefined behavior; see Miri.