Sub topic 4
Why You Cannot Push While Holding a Reference
This chapter assumes you know Rust ownership and borrowing basics (move, &, &mut), you can read Option and match, and you can run programs with cargo. It builds on creating a Vec, reading it with indexing or get, and iterating over it.
By the end you will be able to read the compiler error that appears when you push to a Vec while a reference into it is alive. You will also know why the rule exists and four ways to restructure the code.
The error
Here is the program that triggers the error.
// This does NOT compile.
fn main() {
let mut v = vec![10, 20, 30];
let first = &v[0];
v.push(40);
println!("first = {first}");
}The compiler rejects it with error E0502:
error[E0502]: cannot borrow `v` as mutable because it is also borrowed as immutable
--> src/main.rs:5:5
|
4 | let first = &v[0];
| - immutable borrow occurs here
5 | v.push(40);
| ^^^^^^^^^^ mutable borrow occurs here
6 |
7 | println!("first = {first}");
| ------- immutable borrow later used hereThe message names three places. The shared borrow starts at &v[0]. The mutable borrow starts at v.push(40). The shared borrow is used again afterwards. The conflict exists because all three are true together.
What would go wrong without the rule
A Vec<T> is a small struct on the stack with three fields: a pointer to a heap buffer, a length, and a capacity. The elements live in the heap buffer. &v[0] is a pointer into that buffer, not into the Vec struct.
When push finds that len == capacity, it allocates a bigger buffer, copies the elements across, and frees the old buffer. Any pointer into the old buffer now points at freed memory. In C++ this is iterator invalidation, and using the stale pointer is undefined behavior. Rust turns the same bug into a compile-time error.
The compiler does not check whether this particular push would reallocate. It cannot know, because capacity depends on runtime history. It applies the rule that makes every push safe: a &mut borrow requires that no other borrow of the same value is alive.
The borrow rules, applied
Rust allows either of these at one time for a given value:
- Any number of shared references (
&T). - Exactly one mutable reference (
&mut T).
push has the signature fn push(&mut self, value: T), so calling it needs a mutable borrow of the whole Vec. Indexing with &v[0] creates a shared borrow of the whole Vec, not only of element 0. The borrow checker tracks v, not individual slots. This is why even &v[0] blocks pushing and &v[2] would block it equally.
Every method that takes &mut self conflicts with an outstanding reference: push, pop, insert, remove, retain, sort, dedup, clear, truncate, and extend. Methods that take &self, such as len, get, and iter, can coexist with other shared references.
The borrow ends at the last use
A borrow does not last until the end of the enclosing block. Since Rust 2018, borrows end after their last use. This feature is called non-lexical lifetimes (NLL). This version compiles:
fn main() {
let mut v = vec![10, 20, 30];
let first = &v[0];
println!("first = {first}"); // last use of the reference
v.push(40); // no shared borrow is alive here
println!("{:?}", v);
}The only change from the failing program is the order of two lines. The println! that used first now comes before the push, so the borrow is finished when push runs. If a borrow error surprises you, look for a later use of the reference. Removing or moving that use often fixes it.
Fixing the conflict
There are four common fixes. Pick the one that matches what you need.
Copy the value out
If the element type is Copy, read it into a plain variable. A copy holds no reference, so nothing is borrowed afterwards.
fn main() {
let mut v = vec![10, 20, 30];
let first = v[0]; // copies an i32; no borrow remains
v.push(40);
println!("{first} {:?}", v); // 10 [10, 20, 30, 40]
}Clone the value out
For types such as String, call .clone() to get an independent owned value. This costs an allocation, so use it when you need the data after the mutation.
fn main() {
let mut names = vec![String::from("Ana"), String::from("Bo")];
let first = names[0].clone();
names.push(String::from("Cy"));
println!("{first} {:?}", names); // Ana ["Ana", "Bo", "Cy"]
}Hold an index, not a reference
An index is a plain number and borrows nothing. You re-read the element when you need it, and get makes the lookup safe if the Vec has changed.
fn main() {
let mut v = vec![10, 20, 30];
let pos = 0; // remember where, not a reference
v.push(40);
match v.get(pos) {
Some(x) => println!("element {pos} is {x}"),
None => println!("element {pos} is gone"),
}
}Indices can go stale after remove or insert shifts elements, so you trade a compile-time error for a logic risk. Use them only when you know the layout hasn't changed meaning.
Finish with the reference first
Reorder the code so the last use of the reference comes before the mutation, as in the NLL example above. This costs nothing at runtime.
The same conflict inside a loop
A for loop over &v holds a shared borrow for the entire loop, because the iterator is used on every pass.
// This does NOT compile.
fn main() {
let mut v = vec![1, 2, 3];
for x in &v {
v.push(*x * 2); // error: v is borrowed by the loop
}
}Growing the collection mid-iteration would invalidate the iterator's internal pointer, so the compiler stops it. Build the new items first, then add them after the loop has finished.
fn main() {
let mut v = vec![1, 2, 3];
let doubled: Vec<i32> = v.iter().map(|x| x * 2).collect();
v.extend(doubled); // the iterator borrow ended after collect
println!("{:?}", v); // [1, 2, 3, 2, 4, 6]
}If you really need to mutate while looping, loop over indices. 0..v.len() is evaluated once, and each v[i] read is a short-lived copy.
fn main() {
let mut v = vec![1, 2, 3];
for i in 0..v.len() {
let x = v[i];
v.push(x * 2);
}
println!("{:?}", v); // [1, 2, 3, 2, 4, 6]
}Edge cases
References returned from functions
A reference that comes out of a function call keeps the borrow alive, even if you never wrote & yourself. The signature fn largest(items: &[i32]) -> Option<&i32> ties the returned reference to the input. The compiler therefore treats big below as borrowing v.
// This does NOT compile.
fn largest(items: &[i32]) -> Option<&i32> {
items.iter().max()
}
fn main() {
let mut v = vec![4, 9, 2, 7];
let big = largest(&v);
v.push(1);
println!("{:?}", big);
}Copying the result ends the borrow. Option<&i32>::copied() returns an Option<i32>:
fn largest(items: &[i32]) -> Option<&i32> {
items.iter().max()
}
fn main() {
let mut v = vec![4, 9, 2, 7];
let big = largest(&v).copied(); // Option<i32>, no borrow
v.push(1);
println!("{:?} {:?}", big, v); // Some(9) [4, 9, 2, 7, 1]
}Two mutable references
The rule also forbids let a = &mut v[0]; let b = &mut v[1];, because both borrow all of v. Use v.swap(0, 1) for swapping, or split_at_mut to get two non-overlapping mutable slices.
Summary of the rule
| Situation | Result | Fix |
|---|---|---|
| `let r = &v[0]; v.push(x); use(r);` | Error E0502 | Copy, clone, or reorder |
| `for x in &v { v.push(..) }` | Error E0502 | Collect new items, then `extend` |
| `let r = &v[0]; use(r); v.push(x);` | Compiles (NLL) | None needed |
| `let n = v[0]; v.push(x);` with `i32` | Compiles | None needed |
| `let r = f(&v); v.push(x); use(r);` | Error E0502 | Copy the result, for example with `.copied()` |
Exercise
This code fails with E0502. Name the line that creates the shared borrow, the line that needs the mutable borrow, and the line that keeps the shared borrow alive. Then rewrite it so it compiles and still prints the first word. let mut words = vec![String::from("alpha"), String::from("beta")]; let first = &words[0]; words.push(String::from("gamma")); println!("{first}");
Show answer
The shared borrow is created by &words[0], the mutable borrow is needed by words.push(...), and println!("{first}") keeps the shared borrow alive past the push. Two fixes work. Move the println! above the push, so the borrow ends before the mutation. Or clone the first word: let first = words[0].clone();. The clone is an independent String, so it holds no borrow of words, and the original order of lines then compiles.
Exercise
Why does let first = v[0]; v.push(40); compile for a Vec<i32> when let first = &v[0]; v.push(40); followed by a use of first does not?
Show answer
v[0] on a Vec<i32> copies the integer, because i32 is Copy. The variable first is an independent value and holds no reference into the Vec, so no borrow is alive when push runs. With &v[0], first is a pointer into the heap buffer. A push could reallocate that buffer, so the compiler rejects any later use of the pointer.