Skip to content
Theory · Collections · lesson 3 of 10

Length and capacity

In the previous lesson the row of lockers moved when it ran out of free places. So a row almost always has some slack: there are more lockers than items in them.

Picture renting lockers for a growing collection. If you rent one locker for each new item, you have to move every time. It is wiser to take a row with slack and, once it fills up, move straight to a row twice as long. A vector does exactly that, so it has two different numbers:

Rust
fn main() {
    let mut v: Vec<i32> = Vec::new();
    println!("{} {}", v.len(), v.capacity()); // 0 0
    v.push(1);
    println!("{} {}", v.len(), v.capacity()); // 1 4
    for i in 2..=5 {
        v.push(i);
    }
    println!("{} {}", v.len(), v.capacity()); // 5 8
    for i in 6..=9 {
        v.push(i);
    }
    println!("{} {}", v.len(), v.capacity()); // 9 16
}

Let's walk through the example line by line:

  1. An empty Vec::new() has not taken a single place on the heap yet: length 0, capacity 0.
  2. The first push rents a row for 4 elements at once: length 1, capacity 4.
  3. The fifth element does not fit into a row of four. The vector moves to a row of 8 places: length 5, capacity 8.
  4. The ninth element causes one more move, now to 16 places.

A vector's two sizes

A vector has two sizes:

  • the length len() is how many elements it holds right now;
  • the capacity capacity() is how many elements the space already allocated on the heap can hold.

The capacity is never less than the length. The difference between them is the slack: while there is some, push puts the element into a free place and moves nowhere. The index and get see only the length: a free place holds no element, even though the place is allocated.

How a vector grows

When the slack runs out, push takes three steps:

  1. allocates a new place on the heap, usually twice the old one;
  2. copies all the elements there;
  3. frees the old place.

That is why the capacity of a Vec<i32> grows like this: 0 → 4 → 8 → 16 → 32. These numbers come from a real run on Rust 1.99. The documentation does not promise an exact growth strategy, and code that counts on a particular capacity after push relies on chance.

A move is expensive: all the elements have to be copied. But because of the doubling, moves happen more and more rarely, and on average push stays fast. Interviewers like to ask this: "How does a vector's length differ from its capacity, and what happens when it runs out of space?"

Here the renting analogy falls short. A real move takes time, and you see it, while a vector moves unnoticed, inside an ordinary call to push. You can tell it moved only by the grown capacity.

Space in advance

If you know the number of elements in advance, you can avoid moves altogether:

Rust
fn main() {
    let mut v: Vec<i32> = Vec::with_capacity(3);
    println!("{} {}", v.len(), v.capacity()); // 0 3
    v.push(7);
    println!("{} {}", v.len(), v.capacity()); // 1 3
    let zeros = vec![0; 3];
    println!("{:?} {} {}", zeros, zeros.len(), zeros.capacity()); // [0, 0, 0] 3 3
}

Vec::with_capacity

Vec::with_capacity(3) allocates room for three elements at once but puts none there. The vector is empty: length 0, capacity 3. After push(7) the length becomes 1, while the capacity stays 3: the slack was enough, and there was no move.

vec![0; n]

vec![0; 3] works differently: it creates a vector of three zeros. Here the elements already exist, so both the length and the capacity are 3. Before the semicolon stands the value, after it how many times to repeat it.

Common mistake

A vector from with_capacity is taken for a filled one, and its element is read:

Rust
fn main() {
    let v: Vec<i32> = Vec::with_capacity(3);
    println!("{}", v[0]); // ✗
}
TEXT
index out of bounds: the len is 0 but the index is 0

The program builds but stops with a panic when it runs. with_capacity(3) allocated room, but the vector's length is 0, and the index is compared with the length, not with the capacity. If you need three ready elements, write vec![0; 3], and put elements into a vector from with_capacity with push.

Key points

  • len() is how many elements the vector holds, capacity() is how many the allocated space can hold.
  • When the space runs out, push moves the elements to a new place; a Vec<i32> grows its capacity 0 → 4 → 8 → 16.
  • Vec::with_capacity(n) is an empty vector with capacity n, while vec![0; n] is n zeros.
  • The index is checked against the length: v[0] in an empty vector is a panic, whatever the capacity.