Holding a reference into a Vec and then calling push is the borrow error almost everyone hits first. This part shows why: push can move the whole buffer, and the reference would be left pointing at freed memory.
In Part 7 we met the borrowing rule: many readers or one writer, never both at once. On small examples it can look fussy. This part shows the case where it saves you from a real bug: a reference into a Vec, followed by a push.
We’ll look at how a Vec grows, watch its buffer move to a new address, and then go through the fixes, including one that looks right and that the compiler still rejects. Then we’ll meet the same bug in two other shapes: changing a list while you loop over it, and borrowing one field of a struct while calling a method on the whole thing. Every program here was run on Rust 1.95, and its output is pasted from the run. It builds on Part 6 and Part 7.
Try this first
Read this program and decide what it prints before you scroll down:
fn main() {
let mut v = vec![1, 2, 3];
let first = &v[0];
v.push(4);
println!("first is {first}");
}
Most people guess first is 1. In C++, the same program compiles, and it might print 1, print garbage or crash. In Rust it doesn’t compile:
error[E0502]: cannot borrow `v` as mutable because it is also borrowed as immutable
--> src/main.rs:4:5
|
3 | let first = &v[0];
| - immutable borrow occurs here
4 | v.push(4);
| ^^^^^^^^^ mutable borrow occurs here
5 | println!("first is {first}");
| ----- immutable borrow later used here
The error has three labels, and together they tell a story:
- Line 3 takes a shared borrow of
v.firstis a&i32that points inside the vector. - Line 4 calls
push, which needs&mut v, a mutable borrow. - Line 5 still uses
first, so the shared borrow is alive at line 4.
That’s the rule from Part 7: while a reader exists, there can’t be a writer. But we only added an item at the end. We never touched item 0. Why should reading item 0 conflict with that? To answer that, we need to see what a Vec does when it grows.
A Vec is built like a String
A Vec<T> has the same shape as the String from Part 6. On the stack there are three numbers: a pointer to a buffer on the heap, the length, and the capacity. The items live in the buffer.
- The length is how many items are in the vector.
- The capacity is how many items fit in the buffer before it’s full.
Let’s push items one at a time and print both:
fn main() {
let size = std::mem::size_of::<Vec<i32>>();
println!("a Vec itself takes {size} bytes");
let mut v = Vec::new();
println!("len {}, cap {}", v.len(), v.capacity());
for i in 1..=9 {
v.push(i);
println!("len {}, cap {}", v.len(), v.capacity());
}
}
It prints:
a Vec itself takes 24 bytes
len 0, cap 0
len 1, cap 4
len 2, cap 4
len 3, cap 4
len 4, cap 4
len 5, cap 8
len 6, cap 8
len 7, cap 8
len 8, cap 8
len 9, cap 16
On a 64-bit machine the Vec is 24 bytes, three numbers of 8 bytes each, however many items it holds. An empty Vec::new() has no buffer at all, so its capacity is 0. The first push made room for 4 items. When the fifth item came, the buffer was full, so the vector got a bigger one, with room for 8. At the ninth item it went to 16.
That doubling is what Rust 1.95 does today. The documentation doesn’t promise it. It only promises that pushing stays fast on average, and that capacity() is at least len(). Don’t write code that depends on the exact numbers.
Growing can move the buffer
Here’s the important part. When a buffer is full, the vector asks the allocator for a bigger one. The allocator is the part of the program that hands out heap memory. Sometimes it can stretch the buffer where it is, because the memory right after it is free. Often it can’t. Then it finds a new place, the vector copies its items across, and the old buffer is freed.
as_ptr() gives the address of the buffer. We won’t print the address, because it changes from run to run. We’ll only compare it with the address we started with:
fn main() {
let mut v = vec![1, 2, 3];
let other = vec![7, 8, 9];
let start = v.as_ptr();
v.push(4);
let moved = v.as_ptr() != start;
println!("len {}, cap {}, moved: {moved}", v.len(), v.capacity());
for i in 5..=7 {
v.push(i);
}
let moved = v.as_ptr() != start;
println!("len {}, cap {}, moved: {moved}", v.len(), v.capacity());
println!("{v:?} {other:?}");
}
It prints:
len 4, cap 6, moved: false
len 7, cap 12, moved: true
[1, 2, 3, 4, 5, 6, 7] [7, 8, 9]
vec![1, 2, 3] starts with a capacity of exactly 3, so the first push had to grow it. That time, on this Linux machine, the allocator grew the buffer in place, and the address stayed the same. The second time it grew, the buffer moved. We made other right after v so that its buffer sits next to v‘s and gets in the way. Without it, you may see false both times. A different machine or allocator may give different answers.
That’s the scary part. If a language let you keep first across a push, the program would work most of the time. It would fail only when the buffer happened to move, and only on some machines.
Watching a reference dangle
The animation shows what would happen if Rust let our first program run. As in Part 6, the stack is on the left, the heap is on the right, and a solid arrow means “owns”. A dashed blue arrow is a shared borrow, &.
If Rust allowed it, push would move the items to a new buffer and free the old one, and first would be left pointing at freed memory. The E0502 error is what prevents this.
Here are those steps in words, in case the animation doesn’t play for you:
vholds a length of 3, a capacity of 3 and a pointer to its buffer of1, 2, 3. The buffer is full.let first = &v[0]makesfirsta shared borrow that points at item 0, inside that buffer.v.push(4)needs room for a fourth item, and there isn’t any. The vector asks the allocator for a new buffer with room for 6.- It copies
1, 2, 3into the new buffer, writes4after them, and pointsvat the new buffer. Nowvhas a length of 4 and a capacity of 6. - The old buffer is freed. Nothing updated
first, so it still points into the old buffer. It’s now a dangling reference: a pointer to memory that no longer belongs to the program. println!would read throughfirst. In C or C++ that read is undefined behaviour: it might print 1, print garbage or crash. Rust rejects the program at compile time, so it never runs.
This is why the compiler doesn’t care which item you borrowed. push takes &mut self, and a mutable borrow of the vector is allowed to do anything to it, including move every item somewhere else. The many-readers-or-one-writer rule doesn’t try to work out whether this particular write is harmless. It says no to every write while a reader is alive, and that covers this case without the compiler needing to know about buffers at all.
Four fixes, and one that isn’t
All of the fixes come from the same question: does first need to point into the vector, or do you just need the value?
1. Copy the value out. An i32 is Copy (Part 6), so leave out the &. Now first is its own number, and there’s no borrow at all:
fn main() {
let mut v = vec![1, 2, 3];
let first = v[0];
v.push(4);
println!("first is {first}, v is {v:?}");
}
It prints:
first is 1, v is [1, 2, 3, 4]
2. Clone it. For a type that isn’t Copy, such as String, let first = names[0] would try to move the string out of the vector, and that’s the E0507 error from Part 6. clone gives you your own copy:
fn main() {
let mut names = vec![String::from("Ana"), String::from("Ben")];
let first = names[0].clone();
names.push(String::from("Cai"));
println!("first is {first}, names are {names:?}");
}
It prints:
first is Ana, names are ["Ana", "Ben", "Cai"]
3. Keep an index, not a reference. An index is a plain number. It stays valid when the buffer moves, because it means “item 0 of whatever buffer v has now”:
fn main() {
let mut v = vec![1, 2, 3];
let first = 0;
v.push(4);
println!("first is {}, v is {v:?}", v[first]);
}
It prints:
first is 1, v is [1, 2, 3, 4]
An index has a trap of its own: if you remove items, it can point at a different item, or past the end. Indexing past the end panics, which is loud, but it’s still a bug.
4. Finish with the borrow first. Part 7 showed that a borrow ends at its last use, not at the end of the block. Move the read before the write and there’s no overlap. If you need a reference after the push, take a new one after it:
fn main() {
let mut v = vec![1, 2, 3];
let first = &v[0];
println!("first is {first}");
v.push(4);
println!("v is {v:?}");
}
It prints:
first is 1
v is [1, 2, 3, 4]
Not a fix: Vec::with_capacity. If the problem is that push might move the buffer, why not make the buffer big enough up front? Vec::with_capacity(10) makes an empty vector with room for 10 items, so the next push can’t move anything:
fn main() {
let mut v = Vec::with_capacity(10);
v.extend([1, 2, 3]);
let first = &v[0];
v.push(4);
println!("first is {first}, capacity {}", v.capacity());
}
It prints:
error[E0502]: cannot borrow `v` as mutable because it is also borrowed as immutable
...
4 | let first = &v[0];
| - immutable borrow occurs here
5 | v.push(4);
| ^^^^^^^^^ mutable borrow occurs here
Same error. You know this push is safe. The compiler doesn’t, and it doesn’t try to. The borrow checker looks at types and borrows, never at values like a capacity, which only exist while the program runs. All it sees is that push takes &mut self while first is alive. with_capacity is still worth using when you know how many items are coming, because it saves the copying. It just isn’t a way around the borrow rules.
Worked example: changing a list while you loop over it
This one looks innocent. For every 2 in the list, we want to add a 20 at the end:
fn main() {
let mut v = vec![1, 2, 3];
for x in &v {
if *x == 2 {
v.push(20);
}
}
println!("{v:?}");
}
It prints:
error[E0502]: cannot borrow `v` as mutable because it is also borrowed as immutable
--> src/main.rs:5:13
|
3 | for x in &v {
| --
| |
| immutable borrow occurs here
| immutable borrow later used here
4 | if *x == 2 {
5 | v.push(20);
| ^^^^^^^^^^ mutable borrow occurs here
It’s the same error code as before, and the same bug. Read the labels:
for x in &vborrows the whole vector for the whole loop. Behind the scenes, the loop holds an iterator that points into the buffer and walks along it.- The same
&vis “later used here”, because the loop goes back to it for the next item after each pass. v.push(20)wants&mut vin the middle of that.
If the push moved the buffer, the loop would carry on walking through freed memory. C++ programmers know this as iterator invalidation, and it’s a common crash there.
The fix depends on what you meant. One way is to loop over indexes. Each v[i] is a short borrow that ends straight away, so nothing is held across the push:
fn main() {
let mut v = vec![1, 2, 3];
for i in 0..v.len() {
if v[i] == 2 {
v.push(20);
}
}
println!("{v:?}");
}
It prints:
[1, 2, 3, 20]
0..v.len() is worked out once, before the loop starts, so the new 20 isn’t visited. That’s usually what you want, and it stops a loop like this from running forever.
The other way is to collect what you want to add first, and add it once the loop is over:
fn main() {
let mut v = vec![1, 2, 3];
let mut extra = Vec::new();
for x in &v {
if *x == 2 {
extra.push(20);
}
}
v.extend(extra);
println!("{v:?}");
}
It prints:
[1, 2, 3, 20]
The loop only reads v and only writes extra. Those are two different vectors, so there’s no conflict. extend runs after the loop, when the shared borrow is over.
Worked example: removing and changing items with retain and iter_mut
The other two things people try inside a loop are removing items and changing them. Removing while looping hits the same error. Changing items one at a time is fine, but only if the loop asks for &mut access from the start. Vec has a method for the first job, and a kind of loop for the second.
retain keeps the items you say yes to and removes the rest. You pass it a small inline function, a closure, that answers yes or no for each item. Part 16 covers closures; for now, read |s| *s >= 0 as “given s, keep it if it’s at least 0″. retain hands each item over as a reference, so *s reads the number behind it.
iter_mut loops over the items as &mut references, so you can change each one in place. for s in &mut scores means the same thing.
fn main() {
let mut scores = vec![40, -5, 72, -1, 90];
scores.retain(|s| *s >= 0);
println!("kept: {scores:?}");
for s in scores.iter_mut() {
*s += 10;
}
println!("curved: {scores:?}");
}
It prints:
kept: [40, 72, 90]
curved: [50, 82, 100]
Both work because only one thing has access to the vector at a time. retain borrows it mutably and does all the removing itself, shifting items down in a single pass. The iter_mut loop holds one &mut borrow of the vector, and each s is a writer for one item. You can change items through s, but you can’t call scores.push inside that loop, because scores is already lent out. Changing items is safe. Changing the number of items is what might move the buffer.
Worked example: borrowing two fields at once
Rust tracks borrows of a struct’s fields separately. Part 10 covers structs properly; for now, a struct is a named group of values, called fields. Here’s a shop with a list of items and a log, and a loop that reads one field while it pushes to the other:
struct Shop {
items: Vec<String>,
log: Vec<String>,
}
fn main() {
let mut shop = Shop {
items: vec![String::from("pen"), String::from("ink")],
log: Vec::new(),
};
for item in &shop.items {
shop.log.push(format!("checked {item}"));
}
println!("{:?}", shop.log);
}
It prints:
["checked pen", "checked ink"]
This compiles. &shop.items borrows only the items field, and shop.log.push mutably borrows only the log field. They don’t overlap, so the compiler allows both at once. The same works for a tuple’s fields, pair.0 and pair.1.
Now move the push into a method. A method that takes &mut self borrows the whole struct, whatever its body touches:
struct Shop {
items: Vec<String>,
log: Vec<String>,
}
impl Shop {
fn record(&mut self, line: String) {
self.log.push(line);
}
}
fn main() {
let mut shop = Shop {
items: vec![String::from("pen"), String::from("ink")],
log: Vec::new(),
};
for item in &shop.items {
shop.record(format!("checked {item}"));
}
println!("{:?}", shop.log);
}
It prints:
error[E0502]: cannot borrow `shop` as mutable because it is also borrowed as immutable
--> src/main.rs:18:9
|
17 | for item in &shop.items {
| -----------
| |
| immutable borrow occurs here
| immutable borrow later used here
18 | shop.record(format!("checked {item}"));
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ mutable borrow occurs here
The error now says “borrow shop“, not “borrow shop.log“. When the compiler checks main, it reads only the method’s signature, fn record(&mut self, ...), not its body. As far as main knows, record might change items too, perhaps by pushing to it, which would move the buffer under the loop. So it refuses.
The signature is the promise the compiler checks, so you can change a method’s body later without breaking its callers. The fixes are the ones we already have: touch the field directly, as in the first version, or collect the lines first and call record after the loop.
Tips and traps
- “But I only borrowed item 0.” The borrow checker doesn’t track which item you borrowed. A reference to any item borrows the whole vector, and any
&mutmethod may move every item. Copy the value out, or keep an index. with_capacitydoesn’t silence E0502. Reserving space saves copying, but the compiler never looks at capacities. Restructure the code instead.- An index can go stale too. It can’t dangle, but after a
removeorinsertit may name a different item. If items move around, look them up again by something that doesn’t change, such as a name or an id. - Don’t
pushorremoveinsidefor x in &v. It’s E0502. Collect changes into a second vector and apply them after the loop. To remove items, useretain. To change items, useiter_mut. - The
0..v.len()loop doesn’t see new items. The range is worked out once, before the loop starts. If you want a work list that grows while you process it, use awhile let Some(x) = list.pop()loop instead. It repeats untilpopreturnsNone; Part 11 coversOptionandif let, its one-time form. - A
&mut selfmethod borrows all ofself. Field-by-field borrowing works only when you write the field accesses yourself. If you need a method in the loop, collect first and call it afterwards. - E0502 isn’t the compiler being fussy. When you see it with a collection, ask: “could this call move the buffer my reference points into?” With
VecandString, the answer for any method that adds items is yes.
A reference into a Vec is a pointer into its buffer, and any push might move that buffer, so Rust won’t let the two overlap.
Exercises
Exercise 1. This program should print longest so far: banana, then the list. Fix it in two different ways: once with clone, and once by changing the order of the lines without cloning.
fn main() {
let mut words = vec![String::from("apple"), String::from("banana")];
let longest = &words[1];
words.push(String::from("fig"));
println!("longest so far: {longest}");
println!("{words:?}");
}
It prints:
error[E0502]: cannot borrow `words` as mutable because it is also borrowed as immutable
Exercise 2. Start with let mut temps = vec![21, -40, 23, 999, 19];. Remove the readings below -30 or above 60, then add 1 to each reading that’s left, without writing a loop that pushes or removes. Print the result.
Exercise 3. Without running it, decide whether this compiles, and if so what it prints:
let mut pair = (vec![1, 2, 3], Vec::new());
for x in &pair.0 {
pair.1.push(x * 10);
}
println!("{:?} {:?}", pair.0, pair.1);
Answers
1. With clone, longest is its own String, so there’s no borrow to conflict with the push:
fn main() {
let mut words = vec![String::from("apple"), String::from("banana")];
let longest = words[1].clone();
words.push(String::from("fig"));
println!("longest so far: {longest}");
println!("{words:?}");
}
It prints:
longest so far: banana
["apple", "banana", "fig"]
Without cloning, move the read up so that the borrow ends before the push:
fn main() {
let mut words = vec![String::from("apple"), String::from("banana")];
let longest = &words[1];
println!("longest so far: {longest}");
words.push(String::from("fig"));
println!("{words:?}");
}
It prints:
longest so far: banana
["apple", "banana", "fig"]
2. retain does the removing, and iter_mut does the changing:
fn main() {
let mut temps = vec![21, -40, 23, 999, 19];
temps.retain(|t| *t >= -30 && *t <= 60);
for t in temps.iter_mut() {
*t += 1;
}
println!("{temps:?}");
}
It prints:
[22, 24, 20]
3. It compiles. The loop borrows pair.0 and the push borrows pair.1 mutably. They’re different fields, so the borrows don’t overlap. The Vec::new() gets its item type, Vec<i32>, from the first push.
fn main() {
let mut pair = (vec![1, 2, 3], Vec::new());
for x in &pair.0 {
pair.1.push(x * 10);
}
println!("{:?} {:?}", pair.0, pair.1);
}
It prints:
[1, 2, 3] [10, 20, 30]
x is a &i32, and x * 10 still works, because Rust’s arithmetic operators accept a reference to a number on either side.
What’s next
The compiler has been tracking how long each borrow lives, and so far it has done that silently. In Part 9 we’ll give those lifetimes names, 'a, and see when you have to write them yourself, starting with functions that return references and structs that hold them.