Skip to content
Theory · Collections · lesson 1 of 10

Vec

What you'll learn

What you'll learn:

  • create a vector, add elements to it and read them safely with get;
  • tell a vector's length from its capacity;
  • count the bytes and the characters of a String and get by without s[0];
  • count words with HashMap and entry.
The items of a full row of lockers 0 1 2 move to a row of six, and a bag push goes into the fourth locker

Picture a row of lockers in a changing room. The lockers are numbered from zero, and each one holds one item. The array from theme two works exactly like that, except that its number of lockers is fixed forever: an array [i32; 3] has no place for a fourth number.

But often you don't know in advance how many elements there will be: grades arrive one at a time, words are read from a text. You need a row that can grow. When it runs out of free lockers, such a row moves to a new, longer one and carries all the items over. In Rust such a row is called a vector:

Rust
fn main() {
    let mut v: Vec<i32> = Vec::new();
    v.push(10);
    v.push(20);
    v.push(30);
    println!("{:?} {}", v, v.len()); // [10, 20, 30] 3
    let w = vec![1, 2, 3];
    println!("{:?}", w); // [1, 2, 3]
}

Let's walk through the example line by line:

  1. Vec::new() creates an empty vector, and let mut allows it to change.
  2. Vec<i32> is the type "vector of i32": the element type goes in the angle brackets.
  3. v.push(10) puts a number at the end of the vector. After three calls the vector holds three elements.
  4. {:?} prints the vector in square brackets, and v.len() returns the number of elements, 3.
  5. The vec! macro creates a vector with its elements at once: it is shorter when the elements are known in advance.

What a vector is

A vector Vec<T> is a list of elements of one type that grows and shrinks while the program runs. The letter T here means "any type": there are Vec<i32>, Vec<bool>, Vec<String>. You can't put both numbers and strings into one vector.

The elements live on the heap, in a row, one after another. The variable v itself keeps the address of that place and the size information on the stack, much like a String. A vector owns its elements: when v goes out of scope, all its elements are destroyed too.

Reading an element

There are two ways to read an element by its number.

The index v[i]

You write the number in square brackets, as with an array: v[1] is the second element, because counting starts at zero. If there is no element with that number, the program stops with a panic.

The get method

v.get(i) also looks up an element by its number, but it returns an Option. That is Some with the element if it exists, and None if the number is past the end of the vector. Option is that gift box whose label honestly says it may be empty. There is no panic.

Rust
fn main() {
    let v = vec![10, 20, 30];
    println!("{}", v[1]); // 20
    println!("{:?}", v.get(1)); // Some(20)
    println!("{:?}", v.get(5)); // None
    println!("{}", v[5]); // ✗
}
TEXT
index out of bounds: the len is 3 but the index is 5

Let's walk through it:

  1. v[1] prints 20: that is the second locker.
  2. v.get(1) returns the same element in a wrapper, and {:?} prints Some(20).
  3. v.get(5) returns None: there is no locker number 5.
  4. v[5] compiles, but the program stops with a panic when it runs. How many elements the vector holds becomes known only while the program runs, so the number is checked only then.

You write v[i] when the number is surely valid. If the number comes from outside, from the user or from a calculation, you take get and handle both cases with match.

Looping over a vector

A for loop walks over a vector's elements if you give it a reference &v:

Rust
fn main() {
    let v = vec![10, 20, 30];
    let mut sum = 0;
    for x in &v {
        sum += *x;
    }
    println!("{sum} {}", v.len()); // 60 3
}

for x in &v hands out a reference to each element in turn, and *x gets the number through that reference. The loop only reads the vector, so after the loop v is still intact and v.len() works. If you write for x in v without the &, the loop takes the vector for itself, and after the loop v is moved.

Common mistake

A reference to an element is kept while a new element is added to the vector:

Rust
fn main() {
    let mut v = vec![10, 20];
    let last = &v[1];
    v.push(30); // ✗
    println!("{last}");
}
TEXT
error[E0502]: cannot borrow `v` as mutable because it is also borrowed as immutable

The program does not compile. last is a plain reference to an element, and it is printed after push. But push needs a mutable reference to the whole vector, and the borrowing rules don't let the two live at the same time.

The ban has a real reason. If there are no free lockers, push moves all the elements to a new, longer row and frees the old one. The reference last would then point at an empty locker in the old row.

Here the locker analogy falls short: after the move an element keeps its number, v[1] is still the second element, but its address in memory changes. A reference holds exactly that address, so it would go stale.

The fix is to copy the number instead of taking a reference: let last = v[1];. An i32 is copied, and the vector stays free for push. Interviewers like to ask this: "Why does push not compile while a reference to an element is alive?"

Key points

  • Vec<T> is a growing list of elements of one type: Vec::new() and push, or vec![…] at once.
  • v[i] past the end of the vector is a panic, while v.get(i) returns Some(element) or None.
  • for x in &v reads the elements without taking the vector.
  • While a reference to an element is alive, push does not compile (E0502): it may move the elements to a new place.