Sub topic 1
Quick review: references and borrowing
This chapter refreshes the borrowing rules that lifetimes build on. Lifetimes make no sense without them, so it is worth being precise here.
Prerequisites
You should already be comfortable with:
- Basic Rust syntax: functions, structs, impl blocks, and generics.
- Ownership and moves.
Stringand&str.
If any of these feel shaky, review them first. This chapter does not teach them from scratch.
References borrow instead of own
A reference is an address that lets you use a value without taking ownership of it. Creating one is called borrowing. When the reference goes away, the owner still has its value.
fn length(s: &String) -> usize {
s.len()
}
fn shout(s: &mut String) {
s.push('!');
}
fn main() {
let mut greeting = String::from("hello");
let n = length(&greeting);
shout(&mut greeting);
println!("{greeting} {n}");
}length only reads, so it takes &String. shout changes the string, so it takes &mut String. The caller keeps ownership throughout.
Shared and mutable references
| Kind | Syntax | Can read | Can write | How many at once |
|---|---|---|---|---|
| Shared | `&T` | Yes | No | Any number |
| Mutable | `&mut T` | Yes | Yes | Exactly one, with no shared references alongside |
The rule is often called "aliasing XOR mutability". At any moment, a value has either many readers or one writer, never both.
The rules in practice
The compiler enforces three rules:
- Any number of
&Treferences may exist at the same time. - Only one
&mut Tmay exist at a time, and no&Tmay exist alongside it. - A reference must never outlive the value it points to.
The first two rules prevent data races and surprising mutation. The third is the subject of the rest of this tutorial.
Here is a violation of rule 2:
fn main() {
let mut v = vec![1, 2, 3];
let first = &v[0];
// v.push(4); // error[E0502]: cannot borrow `v` as mutable
println!("{first}");
v.push(4);
println!("{v:?}");
}If the commented-out push were active, first would still be in use afterwards. push may reallocate the vector's buffer, and first would then point at freed memory. The compiler rejects the program. The push after the println! is fine, because first is no longer used by then.
Borrows end at the last use
A borrow does not last until the end of the block. It lasts until the reference is last used. This is why the final push compiles. The next chapters call this idea non-lexical lifetimes. For now, remember that the span in which a reference is alive is a region of the program, and the compiler computes it.
fn main() {
let mut s = String::from("hi");
let r1 = &s;
let r2 = &s;
println!("{r1} {r2}");
let r3 = &mut s;
r3.push_str(", there");
println!("{r3}");
}r1 and r2 are last used in the first println!. After that, &mut s is allowed.
Why this leads to lifetimes
Every reference has a lifetime: the region of code in which it is valid. Usually the compiler works it out without help. Sometimes a function signature leaves it unclear which input a returned reference came from. Then you must say so with a lifetime annotation.
Exercise
This code fails to compile. Which borrowing rule does it break, and how can you fix it without changing what it prints? let mut s = String::from("a"); let r = &s; s.push('b'); println!("{r}");
Show answer
It breaks rule 2: s.push('b') needs a mutable borrow while the shared reference r is still used by the later println!. Fix it by finishing with r first (print it before the push), or by printing s after the push instead of using r.