Sub topic 4
Why You Cannot Push While Holding a Reference
This chapter assumes you know Rust's move and borrow rules (& and &mut), have used Vec::push, and can run programs with cargo.
The conflict
Rust allows many shared references (&T) to a value, or one mutable reference (&mut T), but never both at once. push takes &mut self, so it needs exclusive access to the whole Vec. A reference to an element, such as &v[0], is a shared borrow of the Vec. If that reference is still in use when you call push, the compiler rejects the program.
let mut v = vec![10, 20, 30];
let first = &v[0];
v.push(40);
println!("{first}");This code does not compile. The error looks like this:
error[E0502]: cannot borrow `v` as mutable because it is also borrowed as immutableWhat the rule protects against
A Vec stores its elements in one block of heap memory. When push finds no spare room, the Vec allocates a bigger block, copies the elements over, and frees the old block. A reference taken earlier still points at the old block. Using it would read freed memory, which is a use-after-free bug. Rust rules this out at compile time.
The compiler does not check whether this push would actually reallocate. It rejects every push made while a reference is live.
Fix 1: copy the value
If the element type is Copy, such as i32, copy it out. The copy holds no borrow of the Vec.
fn main() {
let mut v = vec![10, 20, 30];
// Copying the value ends the borrow immediately, so push is allowed.
let first = v[0];
v.push(40);
println!("{first} {:?}", v); // 10 [10, 20, 30, 40]
}For non-Copy types such as String, use .clone() to get an owned copy.
Fix 2: finish with the reference first
A borrow lasts only until its last use, not to the end of the scope. Use the reference, then push.
fn main() {
let mut v = vec![10, 20, 30];
let first = &v[0];
println!("first = {first}"); // last use of the borrow
v.push(40); // allowed: no reference is live now
println!("{:?}", v);
}In the failing version, first is used after push, so the borrow overlaps the mutation. Moving the println! above the push removes the overlap.
Fix 3: keep an index, not a reference
An index is just a number and borrows nothing. Store the position and look the element up again after the push.
fn main() {
let mut v = vec![10, 20, 30];
let pos = 0;
v.push(40);
println!("{:?}", v.get(pos)); // Some(10)
}Summary of options
| Situation | Approach |
|---|---|
| Element is `Copy` | Read it into a new variable |
| Element is not `Copy` | Call `.clone()` |
| Reference is only needed briefly | Use it before calling `push` |
| You need the element later | Keep the index and call `get` again |
Exercise
The code below fails with E0502. Name the line that causes the conflict, and give one change that makes it compile without changing the printed output. let mut names = vec![String::from("Ana")]; let first = &names[0]; names.push(String::from("Bo")); println!("{first}");
Show answer
The conflict is names.push(...), which needs &mut names while first (a shared borrow) is still used by the later println!. Two fixes work. Clone the value with let first = names[0].clone();, or move the println!("{first}"); line above the push. Both give the same output for first.