Sub topic 1
Quick review: references and borrowing
This chapter refreshes the borrowing rules that the rest of the tutorial builds on. Lifetimes make sense only once you are comfortable with what a reference is and what the compiler already checks about it.
Prerequisites
This chapter assumes you already know:
- Basic Rust syntax: functions, structs, impl blocks, and generics.
- Ownership and moves: each value has one owner, and assigning or passing a non-
Copyvalue moves it. - The difference between
String(an owned, growable string) and&str(a borrowed view of string data).
If any of these feel shaky, review them first. This chapter does not teach them from scratch.
What a reference is
A reference is a pointer that borrows a value without taking ownership. You create one with & (shared) or &mut (mutable). The owner keeps responsibility for freeing the value. The reference only lets you use it for a while.
fn main() {
let s = String::from("hello");
let r = &s;
println!("{s} and {r}");
}Both s and r can be read here because r only borrows s. Nothing moved.
Passing a reference to a function is the usual way to let the function read a value without consuming it:
fn length(s: &String) -> usize {
s.len()
}
fn main() {
let name = String::from("Ferris");
let n = length(&name);
println!("{name} has {n} bytes");
}Taking &str instead of &String is more flexible, because a &String coerces to &str automatically. This chapter uses &String here only to keep the example plain.
The two kinds of borrow
| Kind | Syntax | What you can do | How many at once |
|---|---|---|---|
| Shared reference | `&T` | Read | Any number |
| Mutable reference | `&mut T` | Read and write | Exactly one, with no shared references alongside it |
The rule is often summarized as "many readers or one writer". It prevents data races at compile time, and it also prevents bugs in single-threaded code, such as modifying a vector while iterating over it.
fn main() {
let mut v = vec![1, 2, 3];
let first = &v[0];
v.push(4);
println!("{first}");
}
// error[E0502]: cannot borrow `v` as mutable because it is also borrowed as immutablefirst borrows part of v. push may reallocate the vector's buffer, which would leave first pointing at freed memory. The compiler rejects the program because first is still used after the push.
Using mutable references
A &mut reference lets you change the borrowed value in place. The variable that owns the value must itself be declared mut.
fn add_exclamation(s: &mut String) {
s.push('!');
}
fn main() {
let mut greeting = String::from("hello");
add_exclamation(&mut greeting);
println!("{greeting}");
}While the &mut borrow is active, nothing else may read or write greeting. When add_exclamation returns, the borrow ends and greeting is usable again.
How long a borrow lasts
A borrow lasts from the point where the reference is created to the last point where it is used. It does not last until the end of the enclosing block. This is the behavior called non-lexical lifetimes, and a later chapter covers it in detail. For now, the practical effect is that this compiles:
fn main() {
let mut s = String::from("data");
let r1 = &s;
let r2 = &s;
println!("{r1} {r2}");
// r1 and r2 are not used after this line
let r3 = &mut s;
r3.push_str(" more");
println!("{r3}");
}The shared borrows end after the first println!, so the mutable borrow that follows does not conflict with them. If you used r1 after creating r3, the program would fail to compile.
Borrowing from inside a value
References can point to part of a value, not only the whole thing. Indexing, field access, and slicing all produce borrows of the original.
struct User {
name: String,
age: u32,
}
fn main() {
let user = User { name: String::from("Ada"), age: 36 };
let name_ref: &str = &user.name;
let age_ref: &u32 = &user.age;
println!("{name_ref} is {age_ref}");
}A slice such as &s[0..2] is a reference to a range of the original data. Because it borrows from s, it is only valid while s is. That dependency between a reference and the value it came from is exactly what lifetimes describe.
The compiler can track borrows of different fields independently when it sees them directly. In the next example, one field is borrowed mutably and another is read, and that is accepted:
struct Pair {
left: String,
right: String,
}
fn main() {
let mut p = Pair {
left: String::from("L"),
right: String::from("R"),
};
let l = &mut p.left;
let r = &p.right;
l.push('!');
println!("{l} {r}");
}This works because the borrows cover disjoint fields. It stops working if the borrows go through a method call such as p.left_mut(), because the compiler then sees only a borrow of the whole p.
Moves, copies, and references
References themselves are values. A shared reference &T implements Copy, so you can pass it around freely. A mutable reference &mut T does not implement Copy, so using it in a way that would duplicate it moves it, or the compiler reborrows it for a shorter time.
fn bump(n: &mut i32) {
*n += 1;
}
fn main() {
let mut x = 0;
let r = &mut x;
bump(r);
bump(r);
println!("{x}");
}The call bump(r) does not consume r. The compiler inserts an implicit reborrow, &mut *r, that lasts only for the call. That is why r can be used twice.
Dereferencing with * reads or writes the pointed-to value. Method calls and field access dereference automatically, so you rarely write * for them.
What the compiler is already checking
Even without any lifetime syntax, the compiler checks several things about every reference:
- A reference is never null. Use
Option<&T>when a value may be absent. - A shared reference and a mutable reference to the same data are never both live.
- A reference is never used after the data it points to has been moved or dropped.
The third check is the one that leads to lifetimes. In the examples so far, the compiler can verify it by looking at one function body. When a reference crosses a function boundary, as a parameter or a return value, the compiler cannot see the caller's code while checking the callee. It needs a description of how the reference relates to its inputs. That description is a lifetime.
Common mistakes
- Holding a reference across a mutation. Reading from
v[0]through a reference, then callingv.push(...), then using the reference again triggers E0502. - Creating two mutable references to the same value at the same time. This triggers E0499.
- Moving a value while it is borrowed. This triggers E0505, as in the example below.
fn main() {
let s = String::from("hi");
let r = &s;
let t = s;
println!("{r} {t}");
}
// error[E0505]: cannot move out of `s` because it is borrowedWhere this leads
Every example in this chapter kept its references inside one function. The next chapters ask what happens when a reference is returned out of a function, or stored in a struct that outlives the line that created it. In those cases the compiler needs to know how long the reference stays valid, and lifetimes are how you tell it.
Exercise
This program does not compile. Which line causes the error, which error code do you expect, and give one way to fix it without cloning? fn main() { let mut names = vec![String::from("a"), String::from("b")]; let first = &names[0]; names.push(String::from("c")); println!("{first}"); }
Show answer
The call names.push(...) causes the error (E0502). first is a shared borrow of names that is still used afterward, and push needs a mutable borrow. To fix it without cloning, move the println!("{first}"); line before names.push(...), so the shared borrow ends before the mutable one starts.
Exercise
A function takes r: &mut i32 and calls bump(r) twice in a row. Why does this compile even though &mut i32 is not Copy?
Show answer
The compiler inserts an implicit reborrow (&mut *r) for each call. Each reborrow lasts only for that call, so r is not moved and can be used again.