A reference lets you use a value without taking it. Rust allows many shared references or one mutable reference, never both at once. This part shows the rule, the errors it causes, and why a borrow ends at its last use.
In Part 6, every function that read a String had to take ownership of it and then hand it back. This part fixes that. A function can borrow a value instead: it gets a reference to it, uses it, and the owner keeps it.
We’ll cover shared references (&T) and mutable references (&mut T), the one rule that governs them, the compiler errors they cause, and why a borrow ends earlier than you might think. Every program here was run on Rust 1.95, and its output is pasted from the run.
Try this first
Decide whether this compiles, and if it does, what it prints:
fn main() {
let mut s = String::from("hello");
let r = &s;
s.push_str(" world");
println!("{r}");
}
It doesn’t compile:
error[E0502]: cannot borrow `s` as mutable because it is also borrowed as immutable
--> src/main.rs:4:5
|
3 | let r = &s;
| -- immutable borrow occurs here
4 | s.push_str(" world");
| ^^^^^^^^^^^^^^^^^^^^ mutable borrow occurs here
5 | println!("{r}");
| - immutable borrow later used here
s is mut, and it owns the string. So why can’t it change its own string? Because on line 3 it lent the string to r, and r still reads it on line 5. Rust won’t let the string change under a reader’s feet. By the end of this part, you’ll know which of the three labelled lines to move.
Borrowing instead of moving
Here’s Exercise 2 from Part 6 again. letters takes the String, so word is moved and can’t be printed:
fn letters(s: String) -> usize {
s.len()
}
fn main() {
let word = String::from("hello");
let n = letters(word);
println!("{n} letters in {word}");
}
It prints:
error[E0382]: borrow of moved value: `word`
The fix is two characters on each side. The function asks for a &String, a reference to a String, and the caller passes &word:
#[allow(clippy::ptr_arg)]
fn letters(s: &String) -> usize {
s.len()
}
fn main() {
let word = String::from("hello");
let n = letters(&word);
println!("{n} letters in {word}");
}
It prints:
5 letters in hello
&word borrows word. It makes a reference: a value that points at word without owning it. When letters returns, the reference goes away, and nothing is dropped, because a reference owns nothing. word is still the owner.
The #[allow(...)] line turns off one warning from Clippy, Rust’s official linter (cargo clippy). Without it, Clippy says:
error: writing `&String` instead of `&str` involves a new object where a slice will do
...
help: change this to
|
1 + fn letters(s: &str) -> usize {
Clippy is right, and the reason is worth knowing.
Take &str, not &String
Part 5 introduced &str, a borrowed view of some UTF-8 text. A &String can only point at a String. A &str can point at the text inside a String, at a string literal, or at part of either. So a function that only reads text should ask for &str. Here is Part 6’s count_vowels, done properly:
fn count_vowels(text: &str) -> usize {
let mut n = 0;
for c in text.chars() {
if "aeiou".contains(c) {
n += 1;
}
}
n
}
fn main() {
let word = String::from("ownership");
let vowels = count_vowels(&word);
println!("{word} has {vowels} vowels");
println!("banana has {} vowels", count_vowels("banana"));
println!("the first 3 letters have {}", count_vowels(&word[0..3]));
}
It prints:
ownership has 3 vowels
banana has 3 vowels
the first 3 letters have 1
No tuple, no handing the string back. One function now works on a String, a literal and a slice.
We passed a &String to a function that wants a &str, and Rust converted it for us. This is called deref coercion, and Part 22 explains it. For now, read it as “a &String fits wherever a &str is wanted”.
What a reference is in memory
A reference is an address. It points at the place where the value lives:
fn main() {
println!("&i32: {} bytes", std::mem::size_of::<&i32>());
println!("&String: {} bytes", std::mem::size_of::<&String>());
println!("&str: {} bytes", std::mem::size_of::<&str>());
}
It prints:
&i32: 8 bytes
&String: 8 bytes
&str: 16 bytes
On a 64-bit machine, an address is 8 bytes. A &String is one address: it points at the String‘s 24 bytes (on the stack, for a local variable), not at the text on the heap. A &str is 16 bytes, because it carries an address and a length, so it can point at any run of text.
In this series’ figures, an owner is a solid black arrow. A shared reference is a dashed blue arrow, and a mutable reference is a dashed red one.
Changing a value through &mut
A shared reference, &T, can only read. To change a value you don’t own, borrow it with &mut:
fn add_excitement(text: &mut String) {
text.push_str("!!");
}
fn bump(n: &mut i32) {
*n += 1;
}
fn main() {
let mut greeting = String::from("hello");
add_excitement(&mut greeting);
println!("{greeting}");
let mut count = 41;
bump(&mut count);
println!("{count}");
}
It prints:
hello!!
42
Three things to notice:
- The caller writes
&mut greeting, so you can see at the call site that your string may change. - The variable has to be
mut. You can’t lend out the right to change something you can’t change yourself. nis a reference, so*nmeans “the valuenpoints at”. The*is called dereferencing. Without it, Rust would try to add one to the reference itself, and it refuses:cannot use `+=` on type `&mut i32`.
Why doesn’t text.push_str("!!") need a *? Because when you call a method with a dot, Rust follows references for you until it finds the method. This is called auto-deref. You’ll write * for operators like += and =, and almost never for method calls.
The rule: many readers or one writer
At any moment, a value can have either:
- any number of shared references (
&T), or - exactly one mutable reference (
&mut T),
and never both at once. While any reference exists, the owner follows the same rule: it can read, but it can’t change or move the value while shared references are alive, and it can’t even read it while a &mut is alive.
Breaking the first half gives the error from “Try this first”, E0502: a reader is alive and someone wants to write. Breaking the second half gives E0499, two writers at once:
fn main() {
let mut s = String::from("hello");
let a = &mut s;
let b = &mut s;
a.push('!');
b.push('?');
println!("{s}");
}
It prints:
error[E0499]: cannot borrow `s` as mutable more than once at a time
--> src/main.rs:4:13
|
3 | let a = &mut s;
| ------ first mutable borrow occurs here
4 | let b = &mut s;
| ^^^^^^ second mutable borrow occurs here
5 | a.push('!');
| - first borrow later used here
Both errors have the same three labels. One line says where the first borrow started. One says where the conflicting borrow happened. The third, the one people skip, says where the first borrow is used later. That third line is the key to fixing them.
A borrow ends at its last use
A reference doesn’t stay alive until the end of its block. It stays alive until the last line that uses it. After that, the borrow is over, even if the variable is still in scope. The compiler feature behind this is called non-lexical lifetimes: “lexical” would mean “until the closing }“, and Rust doesn’t do that.
So this program compiles, even though it makes two shared borrows and then a mutable one, all in one block:
fn main() {
let mut s = String::from("hi");
let r1 = &s;
let r2 = &s;
println!("{r1} {r2}");
let m = &mut s;
m.make_ascii_uppercase();
println!("{s}");
}
It prints:
hi hi
HI
r1 and r2 are last used in the first println!. Their borrows end there. Then m borrows mutably, and nothing else is borrowing. m is last used on the make_ascii_uppercase line, so by the final println!, the owner s is free to read again.
The animation steps through that program:
Borrows come and go inside one block. Each one ends at its last use, so the two readers are gone before the writer arrives.
Here are those steps in words, in case the animation doesn’t play for you:
let mut s = String::from("hi")makessthe owner of two bytes on the heap. Nothing is borrowed: readers 0, writers 0.let r1 = &sandlet r2 = &smake two shared references. Each one points ats, theStringon the stack. Two readers at once is fine: readers 2, writers 0.- The first
println!printshi hi. It’s the last line that usesr1andr2, so both borrows end right there, not at the closing}. let m = &mut smakes one mutable reference. That’s allowed only because no readers are left.m.make_ascii_uppercase()changes the heap bytes toHandIin place: readers 0, writers 1.mis never used again, so its borrow ends too. The ownerscan read its own string, and the lastprintln!printsHI.
Now look back at “Try this first”. There, r was used on line 5, after the push_str on line 4. Its borrow was still alive when the owner tried to change the string. Move the println!("{r}") above the push_str, and the program compiles.
Explain it like I’m ten
Think of a whiteboard in a classroom. Lots of kids can read it at the same time. But when the teacher wants to write on it, everyone has to stop reading first. Otherwise someone would copy down half a sentence.
And only one person writes at a time. Two people writing on the same spot would scribble over each other.
Reading ends when you look away for the last time, not when the lesson ends. As soon as the last reader is done, the writer can start.
The precise version
&T is a shared reference: an address that is never null and always points at a valid T, and through which the T can’t be changed. &mut T is a unique reference: while it’s alive, no other reference to that value is used, so it can change the value safely.
The part of the compiler that checks this is the borrow checker. For each borrow, it works out the region of code from where the borrow is made to where the reference is last used. If something in that region conflicts with the borrow (another &mut, a shared borrow while a &mut is alive, a write through the owner, or a move), the program doesn’t compile. All of this happens at compile time. At run time, a reference is a plain address, with no counter and no check.
Where the analogy breaks: in the classroom, someone watches while the lesson happens. Rust does all its checking before the program runs, by reading the code. Also, a “reader” in Rust is a shared reference that will be used later, not someone looking at the value. And a few special types allow changes through a shared reference; Part 20 covers them.
References can’t outlive the owner
A reference must never point at a value that’s already been dropped. The compiler checks this too:
fn main() {
let r;
{
let s = String::from("hello");
r = &s;
}
println!("{r}");
}
It prints:
error[E0597]: `s` does not live long enough
--> src/main.rs:5:13
|
4 | let s = String::from("hello");
| - binding `s` declared here
5 | r = &s;
| ^^ borrowed value does not live long enough
6 | }
| - `s` dropped here while still borrowed
7 | println!("{r}");
| - borrow later used here
s is dropped at the inner }, and its heap bytes are freed. If this compiled, r would point at freed memory: a dangling reference. In C, that’s a real bug that reads garbage or crashes. In Rust, it’s E0597. Read the labels again: declared, borrowed, dropped while still borrowed, used later. The fix is to make the owner live longer, by moving let s out of the inner block. Part 9 is all about this, under the name lifetimes.
Shared references are Copy
Part 6 listed &T among the Copy types. That fits the rule: copying a shared reference just makes one more reader, and any number of readers is allowed.
fn main() {
let s = String::from("shared");
let a = &s;
let b = a;
let c = a;
println!("{a} {b} {c} {s}");
}
It prints:
shared shared shared shared
A &mut T is not Copy, because a copy would make two writers. let m2 = m1; moves it, and m1 can’t be used afterwards.
Why the rule exists
The rule can feel strict. Here are the two bugs it prevents.
Data races. If one thread changes a value while another reads it, the reader can see a half-written value. That’s a data race, and in most languages you find it late, in production. To race, two threads need a &mut and another reference to the same value at the same time, and the rule forbids that. Part 23 shows it with real threads.
Changing a collection while you read it. Say first = &names[0], and then you push a new name. If the vector is full, push moves all its items to a bigger buffer on the heap and frees the old one. Now first points at freed memory. The rule catches it: push needs &mut names, and first is still a shared borrow. That’s Part 8, with an animation of exactly that move.
Both bugs need someone reading and someone changing at the same time. The rule allows one or the other.
Worked example: a slice that blocks a change
You keep a log in a String and want its first word. You take a slice, then add to the log:
fn main() {
let mut log = String::from("start: ok");
let first = &log[0..5];
log.push_str(", stop: ok");
println!("first word: {first}");
println!("{log}");
}
It prints:
error[E0502]: cannot borrow `log` as mutable because it is also borrowed as immutable
--> src/main.rs:4:5
|
3 | let first = &log[0..5];
| --- immutable borrow occurs here
4 | log.push_str(", stop: ok");
| ^^^^^^^^^^^^^^^^^^^^^^^^^^ mutable borrow occurs here
5 | println!("first word: {first}");
| ----- immutable borrow later used here
Read it line by line:
- Line 3, “immutable borrow occurs here”.
&log[0..5]is a&strthat points intolog‘s heap bytes. That’s a shared borrow oflog. - Line 4, “mutable borrow occurs here”.
push_stris declared asfn push_str(&mut self, ...), so calling it borrowslogmutably. You didn’t write&mut, but the method call did it for you. - Line 5, “immutable borrow later used here”. This is why line 3’s borrow is still alive at line 4.
push_str might move the text to a bigger buffer, and first would point at the old one. So there are two honest fixes. If you only need the first word before the change, use it before the change:
fn main() {
let mut log = String::from("start: ok");
let first = &log[0..5];
println!("first word: {first}");
log.push_str(", stop: ok");
println!("{log}");
}
It prints:
first word: start
start: ok, stop: ok
If you need the word after the change, make it a String of its own with let first = log[0..5].to_string();. Then it no longer borrows log, and the original order compiles. That fix copies five bytes, and the first one copies nothing, so prefer moving the use when you can.
Worked example: updating two scores
A game keeps scores in a Vec<u32>. A rule gives a point to the first and the last player. The obvious code takes two &mut:
fn main() {
let mut scores = vec![10, 20, 30];
let first = &mut scores[0];
let last = &mut scores[2];
*first += 1;
*last += 1;
println!("{scores:?}");
}
It prints:
error[E0499]: cannot borrow `scores` as mutable more than once at a time
--> src/main.rs:4:21
|
3 | let first = &mut scores[0];
| ------ first mutable borrow occurs here
4 | let last = &mut scores[2];
| ^^^^^^ second mutable borrow occurs here
5 | *first += 1;
| ----------- first borrow later used here
|
= help: use `.split_at_mut(position)` to obtain two mutable non-overlapping sub-slices
Items 0 and 2 are different numbers, so why the error? Look where the labels point: at scores, not at scores[0]. Indexing a Vec calls a method that borrows the whole vector mutably. The compiler doesn’t check which index you passed. So first holds a &mut to all of scores, and last asks for a second one.
The help line’s split_at_mut works, but the simplest fix is to finish one borrow before starting the next. A small function makes that natural:
fn add_points(score: &mut u32, points: u32) {
*score += points;
}
fn main() {
let mut scores = vec![10, 20, 30];
add_points(&mut scores[0], 1);
add_points(&mut scores[2], 1);
println!("{scores:?}");
let total: u32 = scores.iter().sum();
println!("total {total}");
}
It prints:
[11, 20, 31]
total 62
Each &mut scores[...] lives only for one call, so the borrows never overlap. The iter().sum() line borrows scores shared, which is fine, because no &mut is alive. Part 17 covers iterators.
Tips and traps
- Forgetting
muton the owner.let s = ...; let m = &mut s;fails with E0596,cannot borrow `s` as mutable, as it is not declared as mutable. The fix islet mut s. The compiler’shelpline shows exactly where. - Forgetting
*with operators.n += 1wheren: &mut i32fails with E0368. Write*n += 1. Method calls liketext.push_str(...)don’t need the*. - Fixing E0502 or E0499 with
.clone(). It often compiles, but now you have a copy, and changes no longer reach the original. First find the “later used here” line: it’s what keeps the borrow alive. Moving that use earlier is usually the real fix. - Taking
&Stringor&Vec<T>as a parameter. Clippy warns. Take&stror&[T]instead, and callers can pass aString, a literal, aVecor a slice. - Method calls borrow too.
log.push_str(...)borrowslogmutably, andv.len()borrows it shared, even though you never typed&. Count them when you read an error.
Any number of readers, or exactly one writer, and a borrow ends at its last use.
Exercises
Exercise 1. Without running it, decide whether this compiles, and if so, what it prints:
let name = String::from("Ana");
let a = &name;
let b = a;
println!("{a} and {b} both read {name}");
Exercise 2. Write a function add_suffix that takes a &mut String and a &str and adds the suffix to the end. Use it so that main prints report.txt from a String that starts as report.
Exercise 3. This program fails with E0499. Fix it so it prints 2, without adding new variables and without clone. You may reorder lines.
fn main() {
let mut count = 0;
let a = &mut count;
let b = &mut count;
*a += 1;
*b += 1;
println!("{count}");
}
It prints:
error[E0499]: cannot borrow `count` as mutable more than once at a time
Answers
1. It compiles. a is a shared reference, and shared references are Copy, so let b = a copies it. Now there are two readers, and the owner name reads too. Nobody writes, so the rule is satisfied.
fn main() {
let name = String::from("Ana");
let a = &name;
let b = a;
println!("{a} and {b} both read {name}");
}
It prints:
Ana and Ana both read Ana
2. The string to change is borrowed with &mut, and the suffix only needs to be read, so it’s a &str. push_str is a method, so no * is needed.
fn add_suffix(text: &mut String, suffix: &str) {
text.push_str(suffix);
}
fn main() {
let mut file = String::from("report");
add_suffix(&mut file, ".txt");
println!("{file}");
}
It prints:
report.txt
3. Use a before b is made. a‘s last use is *a += 1, so its borrow ends there, and b can borrow afterwards. By the println!, both borrows are over, and the owner can read.
fn main() {
let mut count = 0;
let a = &mut count;
*a += 1;
let b = &mut count;
*b += 1;
println!("{count}");
}
It prints:
2
What’s next
The rule is easy to state and easy to break by accident, mostly with collections. In Part 8, we’ll watch a Vec move to a bigger buffer when you push, see why that would leave a reference pointing at freed memory, and learn the usual patterns for reading and changing a collection in the same piece of code.