Sub topic 1
Creating and growing a Vec
Prerequisites
This chapter assumes you know basic Rust syntax (variables, functions, structs and enums). It also assumes you understand ownership and borrowing basics (move, &, &mut), that you can read Option and match, and that you can run programs with cargo run. Every example is a complete main.rs you can paste into a new project.
What a Vec is
Vec<T> is a growable, heap-allocated list of values that all have the same type T. It is the collection you will reach for first in Rust. An array such as [i32; 4] has a length fixed at compile time. A Vec can change its length while the program runs.
A Vec is a small value on the stack made of three fields. These are a pointer to a heap buffer, a length (len, how many elements are stored) and a capacity (capacity, how many elements fit before the buffer must be replaced). The elements sit next to each other in memory. The Vec owns that buffer. When the Vec goes out of scope, it drops every element and frees the buffer.
Creating a Vec
There are two common ways to create one. Vec::new() makes an empty Vec and allocates nothing yet. The vec! macro makes a Vec with initial contents.
fn main() {
let mut scores: Vec<i32> = Vec::new();
scores.push(90);
scores.push(72);
let primes = vec![2, 3, 5, 7];
println!("{:?}", scores.get(1)); // Some(72)
println!("{:?}", scores.get(5)); // None
println!("{}", primes[2]); // 5
println!("{:?}", scores.pop()); // Some(72)
}Vec::new() needs a type. Here the annotation Vec<i32> supplies it. Without an annotation, the compiler infers T from later use, such as the first push. If it cannot infer a type, you get error E0282 ("type annotations needed").
vec! also has a repeat form, vec![0; 5], which makes [0, 0, 0, 0, 0]. The repeated value must implement Clone, because the macro clones it to fill the other slots.
Other constructors you will meet:
Vec::from([1, 2, 3])or[1, 2, 3].to_vec()copy an array into aVec.Vec::with_capacity(n)reserves space up front. A later chapter covers it.iterator.collect::<Vec<_>>()builds aVecfrom an iterator. A later chapter covers this too.
Growing and shrinking
push appends one element to the end. pop removes the last element and returns it as an Option<T>, because an empty Vec has nothing to pop. Both work at the end of the Vec, so they are cheap.
Both need the Vec to be declared mut. Forgetting that is the most common beginner error here:
fn main() {
let v = Vec::new();
v.push(1); // error[E0596]: cannot borrow `v` as mutable
}The fix is let mut v = Vec::new();.
Because pop returns an Option, it fits naturally in a while let loop. This loop drains a Vec from the back:
fn main() {
let mut stack = vec![1, 2, 3];
while let Some(top) = stack.pop() {
println!("popped {top}");
}
println!("empty: {}", stack.is_empty()); // empty: true
}The output is popped 3, popped 2, popped 1, then empty: true. This last-in, first-out pattern is how a Vec works as a stack.
Other ways to add elements in bulk:
| Method | What it does |
|---|---|
| `push(x)` | Appends one element |
| `extend(iter)` | Appends every item from an iterator |
| `append(&mut other)` | Moves all of `other`'s elements onto the end, leaving `other` empty |
| `clear()` | Removes all elements but keeps the allocated buffer |
fn main() {
let mut a = vec![1, 2];
let mut b = vec![3, 4];
a.extend([10, 20]);
a.append(&mut b);
println!("{:?} {:?}", a, b); // [1, 2, 10, 20, 3, 4] []
}What happens when a Vec grows
When push is called and len == capacity, the Vec must allocate a bigger buffer, move the existing elements into it, and free the old one. This is a reallocation. The standard library grows the capacity geometrically (it is amortized, with the exact factor left unspecified), so a long series of pushes costs O(1) per push on average. A single push that triggers a reallocation costs O(n), because every element moves.
You can watch this happen by printing the capacity after each push:
fn main() {
let mut v: Vec<u8> = Vec::new();
let mut last_cap = v.capacity();
println!("start: cap {last_cap}");
for i in 0..40 {
v.push(i);
if v.capacity() != last_cap {
last_cap = v.capacity();
println!("len {} -> cap {}", v.len(), last_cap);
}
}
}On current stable compilers, a Vec<u8> starts at capacity 0, jumps to 8 on the first push, and then doubles. The exact numbers are an implementation detail that can change between Rust versions, so never rely on them in real code.
Reallocation matters for one more reason. The elements may move to a new address. Any reference pointing into the old buffer would then dangle. This is why the borrow checker refuses to let you hold a reference into a Vec while you push to it. A later chapter explains this rule in detail.
Common errors
- Forgetting
mut.push,pop,clearandextendall take&mut self. Withoutmuton the binding you get E0596. - Mixing element types.
vec![1, "two"]fails with a mismatched types error, because aVecstores one type. A later chapter shows how to use an enum to work around this. - Ambiguous literals.
vec![1, 2, 3]defaults toVec<i32>. If you later pass it whereVec<u64>is expected, the compiler infersu64for the literals instead, and that usually works. A mismatch only occurs if you use the values as two different integer types. - Using a
Vecafter moving it. Passing aVecby value to a function moves it. Pass&vor&mut vif the caller still needs it. - Confusing
lenwithcapacity.Vec::with_capacity(10)has length 0. You cannot index position 5 of it, because no element exists there yet.
The last two points combine in this example:
fn total(items: Vec<i32>) -> i32 {
items.iter().sum()
}
fn main() {
let v = vec![1, 2, 3];
let t = total(v);
println!("{t}");
// println!("{:?}", v); // error[E0382]: borrow of moved value: `v`
}Changing the parameter to items: &[i32] and calling total(&v) lets main keep using v. Slices are covered in a later chapter.
Summary of the working model
A Vec<T> is a pointer, a length and a capacity. push and pop work at the end. Growth beyond capacity moves the elements to a new buffer. Ownership of the elements belongs to the Vec. Mutating methods require mut.
Exercise
This program does not compile. Give the two changes needed, and say what it prints afterward. fn main() { let v = Vec::new(); v.push(5); v.push(6); println!("{:?} {:?}", v.pop(), v); }
Show answer
Declare the binding as let mut v = Vec::new();, because push and pop need &mut. The second change is to give the compiler a type. The push(5) call lets it infer Vec<i32>, so no annotation is strictly required there. But the println! still fails, because the arguments v.pop() and v borrow v mutably and immutably in one macro call. Compute the pop first: let top = v.pop(); println!("{:?} {:?}", top, v);. It then prints Some(6) [5].
Exercise
You start with let mut v: Vec<u8> = Vec::new(); and push 100 elements one at a time. Does v.capacity() equal 100 afterward? What can you say about it, and which constructor would avoid the intermediate reallocations?
Show answer
No, you can only say v.capacity() >= 100, and the exact value depends on the growth strategy of the standard library (it is typically a power of two such as 128). Vec::with_capacity(100) reserves space for at least 100 elements up front, so the 100 pushes cause no reallocation.