Vectors: Storing Lists

Vectors: Storing Lists in Rust: A row of identical seats is bolted to a single steel beam, in order, and the first one is numbered 0.

The Analogy: The Row of Bolted Seats

A row of identical seats is bolted to a single steel beam, in order, and the first one is numbered 0. Because they are identical and evenly spaced, nobody has to walk down the row to find seat 5 -- you measure five spacings from the end of the beam and you are there. That is the whole reason the row exists rather than a scattering of chairs: fixed size, fixed spacing, one continuous beam, so any seat is instantly reachable.

The beam is longer than the seats currently on it. There is spare steel at the far end, and while there is spare steel, adding a seat is a two-minute job with a spanner. The row has a length -- how many seats are bolted on -- and separately a capacity, which is how many the current beam could take. Those two numbers are almost never equal.

When the spare steel runs out, something more dramatic happens. The workshop brings a longer beam, and every existing seat is unbolted and re-bolted onto it in the same order. From the audience's point of view nothing changed: seat 0 is still first, seat 5 is still sixth. But the row is physically somewhere else now, and anybody who wrote down "the seat at this exact spot on the floor" is holding a note about a place where no seat sits any more.

That last sentence is the reason Rust will not let you keep a reference into a vector while you add to it. It is not being fussy: the compiler cannot know whether your next push is the one that fills the beam, so it refuses the whole pattern. Everything else about vectors follows from these four facts -- one type per row, contiguous storage, length separate from capacity, and a move when the capacity runs out.


Syntax or Core Structure

Vec<T> is a growable, heap-allocated list of one type. Build it empty with Vec::new or from known values with the vec! macro.

fn main() {
    let mut readings: Vec<i32> = Vec::new();
    readings.push(21);
    readings.push(19);
    readings.push(24);

    let ports = vec![80, 443, 8080];

    println!("readings {:?}", readings);
    println!("ports {:?}", ports);
    println!("first port {}", ports[0]);
    println!("len {}, empty {}", readings.len(), readings.is_empty());

    let last = readings.pop();
    println!("popped {:?}, left {:?}", last, readings);

    let mut total = 0;

    for r in &readings {
        total += r;
        println!("  reading {r}");
    }

    println!("total {total}");
}

Output:

readings [21, 19, 24]
ports [80, 443, 8080]
first port 80
len 3, empty false
popped Some(24), left [21, 19]
  reading 21
  reading 19
total 40

The type annotation on readings is needed because an empty Vec::new() gives the compiler nothing to infer T from. ports needs no annotation -- vec![80, 443, 8080] is obviously a Vec<i32>. And pop returns Option<T> rather than T, because popping an empty vector has to mean something, and None is that something.

Reading an element: two different promises

Square brackets are the short form, and they panic if the index is past the end. get is the checked form, and it hands back an Option.

fn main() {
    let ports = vec![80, 443, 8080];

    match ports.get(7) {
        Some(p) => println!("port {p}"),
        None => println!("no port at index 7"),
    }

    println!("{}", ports[7]);
}

Output:

no port at index 7
thread 'main' panicked at src/main.rs:9:20:
index out of bounds: the len is 3 but the index is 7
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace

Column 20 on line 9 is where ports[7] starts, which is how the panic knows what to point at. The panic text goes to standard error while the println! above went to standard output, so if you pipe the two streams separately you will see them apart; in a terminal they arrive in this order.

The rule of thumb: use [] when the index is one you just derived from the vector itself and cannot be wrong, and get at every boundary where the number came from outside -- a config file, a user, a parsed line.


Technical Depth: Length, Capacity, and the Move

Two numbers, not one

len() is how many elements are in the vector. capacity() is how many it could hold before the next reallocation. Watch both as a vector grows.

fn main() {
    let mut v: Vec<u32> = Vec::new();
    println!("{:<8} len {} cap {}", "start", v.len(), v.capacity());

    for n in 1..=9 {
        v.push(n);
        println!("{:<8} len {} cap {}", format!("push {n}"), v.len(), v.capacity());
    }

    v.clear();
    println!("{:<8} len {} cap {}", "clear", v.len(), v.capacity());
}

Output:

start    len 0 cap 0
push 1   len 1 cap 4
push 2   len 2 cap 4
push 3   len 3 cap 4
push 4   len 4 cap 4
push 5   len 5 cap 8
push 6   len 6 cap 8
push 7   len 7 cap 8
push 8   len 8 cap 8
push 9   len 9 cap 16
clear    len 0 cap 16

Three things in that output are worth separating carefully, because only two of them are promises.

Guaranteed. Vec::new() does not allocate at all -- capacity starts at 0 and no heap memory is touched until the first push. Capacity never shrinks on its own: clear set the length to 0 and left the 16-element allocation exactly where it was. And pushing is amortised O(1), meaning the occasional expensive reallocation is paid for by the many cheap pushes around it.

Not guaranteed. The specific sequence 0, 4, 8, 16 is what the current standard library happens to do -- a first allocation of 4 for small element types, then doubling. Nothing in Vec's documented contract says those numbers, and code that depends on them is code that can break on a compiler upgrade. Read the shape (it grows in jumps, and the jumps get bigger), not the digits.

If you want the memory back after a clear, ask for it with shrink_to_fit(). If you know up front roughly how many elements are coming, Vec::with_capacity(n) makes one allocation instead of a staircase of them.

Why a reference blocks a push

Because a full vector moves to a new allocation, any reference into the old one would be left pointing at freed memory. The compiler will not let that situation exist, so it rejects the pattern before it can happen.

fn main() {
    let mut v = vec![1, 2, 3];
    let first = &v[0];
    v.push(4);
    println!("{}", first);
}
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);
  |                    ----- immutable borrow later used here

Notice that the error is not about the push alone -- it needs all three lines. Delete the println! and the code compiles, because the borrow's last use is then before the push and the reference is dead by the time the vector moves. That is non-lexical lifetimes at work: the borrow lasts until its final use, not until the end of the block.

There are two honest fixes and one dishonest one. Copy the value out (let first = v[0];, which for i32 copies four bytes and owes the vector nothing afterwards). Or reorder so all the pushing finishes before any borrowing starts. The dishonest fix is to note the index instead of the reference and re-index later -- that compiles, but if something removed an element in between, index 0 is now a different element and no compiler will tell you.

Every way to reach an element

ExpressionYieldsPast the end
v[i]the element itself, usable directly when T: Copypanics
&v[i]&Tpanics
&mut v[i]&mut Tpanics
v.get(i)Option<&T>None
v.get_mut(i)Option<&mut T>None
v.first(), v.last()Option<&T>None when empty

The index must be a usize. An i32 loop counter will not index a vector, which is a small annoyance that turns out to be a real guard: a negative index cannot even be expressed.

Three ways to loop, three different meanings

fn main() {
    let mut temps = vec![18, 21, 25, 19];

    let mut hottest = temps[0];

    for t in &temps {
        if *t > hottest {
            hottest = *t;
        }
    }

    println!("hottest {hottest}");

    for t in &mut temps {
        *t += 1;
    }

    println!("adjusted {:?}", temps);

    let names = vec![String::from("north"), String::from("south")];

    for name in names {
        println!("site {name}");
    }
}

Output:

hottest 25
adjusted [19, 22, 26, 20]
site north
site south

&temps borrows: each t is a &i32, which is why comparing needs *t, and the vector is untouched and usable afterwards. &mut temps gives each t as &mut i32, and *t += 1 writes through it, editing in place with no second vector allocated. Plain names consumes the vector -- each name is an owned String, and names cannot be used after the loop at all. That third form is the right one when the elements are what you actually wanted and the container was just transport.

One vector, one type

A Vec<T> stores exactly one T. When the data genuinely varies, the variation goes inside an enum, not inside the vector.

enum Cell {
    Text(String),
    Number(f64),
    Empty,
}

fn render(c: &Cell) -> String {
    match c {
        Cell::Text(s) => s.clone(),
        Cell::Number(n) => format!("{n:.2}"),
        Cell::Empty => String::from("-"),
    }
}

fn main() {
    let row = vec![
        Cell::Text(String::from("widget")),
        Cell::Number(12.5),
        Cell::Empty,
        Cell::Number(3.0),
    ];

    for c in &row {
        println!("{}", render(c));
    }
}

Output:

widget
12.50
-
3.00

This is the same trade as everywhere else in Rust: the enum costs you a match at every use, and buys you the guarantee that there is no fourth kind of cell you forgot about. The alternative that people reach for first -- parallel vectors, one per field, kept in step by hand -- has no such guarantee and drifts the first time a bug removes from one and not the other.

The operations worth knowing, and what they cost

MethodWhat it doesCost
push(x)append to the endamortised O(1)
pop()remove the last, as Option<T>O(1)
insert(i, x)insert, shifting the rest rightO(n)
remove(i)remove, shifting the rest left, returns TO(n)
swap_remove(i)remove by moving the last into the gapO(1), reorders
truncate(n)drop everything from index n onO(n) drops
retain(f)keep only elements where f is trueO(n), one pass
sort()sort in place, needs T: OrdO(n log n)
dedup()remove consecutive duplicatesO(n)
contains(&x)linear search, needs T: PartialEqO(n)
with_capacity(n)allocate room for n up frontone allocation

Two of those hide a trap. dedup only collapses runs, so on [1, 2, 1] it removes nothing -- sort first if you meant "unique". And sort() needs Ord, which f64 does not implement because NaN is not ordered against anything; sorting floats means sort_by with an explicit comparison and a decision about what NaN should do.


Real World Example: Working a Print Queue

A print queue is a vector's natural habitat: jobs arrive at the end, get reordered by priority, get taken off the front, and occasionally get thrown out of the middle. Every one of those is a different method with a different cost.

struct Job {
    id: u32,
    owner: String,
    pages: u32,
    urgent: bool,
}

fn job(id: u32, owner: &str, pages: u32, urgent: bool) -> Job {
    Job {
        id,
        owner: String::from(owner),
        pages,
        urgent,
    }
}

fn line(j: &Job) -> String {
    let flag = if j.urgent { "!" } else { " " };
    format!("{} #{:<3} {:<6} {:>3}p", flag, j.id, j.owner, j.pages)
}

fn main() {
    let mut queue: Vec<Job> = Vec::with_capacity(8);

    queue.push(job(101, "ada", 12, false));
    queue.push(job(102, "ravi", 400, false));
    queue.push(job(103, "mei", 3, true));
    queue.push(job(104, "ada", 0, false));
    queue.push(job(105, "sam", 45, true));

    println!("submitted {} jobs, capacity {}", queue.len(), queue.capacity());

    queue.retain(|j| j.pages > 0);
    println!("after dropping empty jobs: {}", queue.len());

    queue.sort_by_key(|j| (!j.urgent, j.pages));

    println!();

    for j in &queue {
        println!("{}", line(j));
    }

    let first = queue.remove(0);

    println!();
    println!("printing #{} for {} ({} pages)", first.id, first.owner, first.pages);

    let mut i = 0;

    while i < queue.len() {
        if queue[i].pages > 100 {
            let big = queue.swap_remove(i);
            println!("deferring #{} ({} pages)", big.id, big.pages);
        } else {
            i += 1;
        }
    }

    println!();
    println!("remaining {} jobs, capacity {}", queue.len(), queue.capacity());

    for j in &queue {
        println!("{}", line(j));
    }
}

Output:

submitted 5 jobs, capacity 8
after dropping empty jobs: 4

! #103 mei      3p
! #105 sam     45p
  #101 ada     12p
  #102 ravi   400p

printing #103 for mei (3 pages)
deferring #102 (400 pages)

remaining 2 jobs, capacity 8
! #105 sam     45p
  #101 ada     12p

Every method in that program was chosen for its cost, not for how it reads. retain walks the vector once and slides survivors down as it goes, so dropping the empty job cost one pass rather than a second vector. sort_by_key is one O(n log n) sort with the priority rule expressed as a tuple: (!j.urgent, j.pages) sorts false before true, so negating urgent puts urgent jobs first, and pages breaks the tie in favour of the short jobs. remove(0) shifts every remaining element left one slot -- trivial for a four-element queue, and exactly the wrong call for a queue of a hundred thousand.

swap_remove is the interesting one. It fills the gap with the last element instead of shifting, which makes it O(1), and it pays for that by scrambling the order. Here it removed job 102, which happened to be the last element, so nothing moved and the sorted order survived. That was luck, not design: had the 400-page job been in the middle, the sort would have been silently undone. It is the right tool when order does not matter and a bug waiting to happen when it does.

Ownership shows up twice, quietly. remove(0) hands back the whole Job by value, including its String, which is why first.owner still prints after the job has left the vector -- nothing was cloned and nothing dangles. The two for j in &queue loops borrow instead, which is why the same vector can be printed, mutated, and printed again. Neither choice is about speed; each is a statement about who owns the element next.

The honest limits. Capacity stayed at 8 through all of it, even after three jobs left -- a vector never returns memory unasked, which is ideal for a queue that will refill and a leak-shaped surprise if you drained a huge one and kept it alive. with_capacity(8) is a guarantee of at least 8, and the figure printed back matches only because nothing here forced a growth; the growth sequence itself is not contractual. line() allocates a fresh String per row for the sake of one println!. The |j| ... arguments to retain and sort_by_key are closures, which Module 7 covers properly. And encoding "urgent first" as a negated boolean inside a sort key works but hides policy in a !; a system with three priority levels rather than two should give Job a real priority field and sort on that.


Common Mistakes

  1. Indexing with a number that came from outside. v[i] where i was parsed from a file or typed by a user is a panic waiting for the wrong input. Use v.get(i) and handle the None. Reserve [] for indices you derived from the vector itself.
  1. Holding a reference across a push. let first = &v[0]; v.push(4); println!("{}", first); is E0502. The compiler cannot know whether that push is the one that reallocates, so it rejects every such pattern. Copy the value out, or finish growing before you start borrowing.
  1. Treating remove(0) as cheap. It shifts every remaining element down one slot, so removing the front of an n-element vector n times is O(n squared). If the front is where your work happens, VecDeque is the container you actually wanted.
  1. Calling dedup on unsorted data. It only collapses runs of equal neighbours. On [1, 2, 1] it removes nothing at all. Sort first, or you have written a function that removes duplicates only sometimes.
  1. Expecting clear or truncate to give memory back. Both set the length; neither touches the allocation. A vector that once held a million elements still holds a million elements' worth of heap after clear. shrink_to_fit is the explicit ask.
  1. Trying to mix types in one vector. vec![1, "two"] cannot compile -- there is no single T. Put the variation in an enum and store Vec<Cell>, or use a tuple if the shape is fixed and positional.
  1. Consuming a vector by accident. for x in v moves v into the loop, and every later use of v is then E0382. The fix is one character: for x in &v.
  1. Reaching for sort() on floats. f64 is not Ord, because NaN compares equal to nothing, so v.sort() will not compile on Vec<f64>. You must use sort_by with partial_cmp and decide deliberately what happens to NaN.
  1. Writing v[v.len() - 1] on a vector that might be empty. With length 0 the subtraction itself is the bug: in a debug build 0usize - 1 panics with "attempt to subtract with overflow", and in a release build it wraps to a colossal number and the index panics instead. v.last() gives you Option<&T> and never does either.

Best Practices

  • Use Vec::with_capacity(n) whenever you have a rough n. One allocation instead of a staircase of them, for the cost of one extra argument. Even a wrong guess in the right order of magnitude beats starting from zero.
  • Choose [] or get deliberately, per site. [] says "this index cannot be out of range and I want a loud crash if I am wrong". get says "this might miss and I have a plan". Both are correct; picking one by habit is what goes wrong.
  • Do your adding and removing at the end. push and pop are the operations Vec is actually built for. Needing the front repeatedly is a signal about the data structure, not a problem to solve with cleverer indexing.
  • Pick between remove and swap_remove on purpose, and say which in a comment. swap_remove is free and destroys ordering; remove preserves ordering and costs a shift. A reader six months later cannot tell which property you were relying on.
  • Default to for x in &v. Use &mut v when you are editing in place and plain v only when consuming the vector is the point. Making that choice explicit at every loop documents your intent for free.
  • Store one type; put the variation in an enum. Parallel vectors kept in step by hand look simpler and are one bug away from being permanently misaligned, with nothing to catch it.
  • Filter with retain rather than building a second vector. One pass, no new allocation, and the intent -- "keep these" -- is on the page instead of implied by a loop.
  • Take &[T] in function parameters, not &Vec<T>. A slice parameter accepts vectors, arrays, and sub-ranges alike, and it advertises that the function only reads. &Vec<T> demands a specific container for no benefit.

Practice Exercises

  1. Turn the queue around. Rewrite the print-queue program so the next job is taken from the end with pop instead of the front with remove(0), adjusting the sort key so the highest-priority job lands last. Then write two sentences on what the change cost you in readability and bought you in complexity.
  1. Break the borrow checker on purpose. Write the &v[0] then push then print sequence, read the three spans in the E0502 output, and identify which line the compiler blames versus which line it says the borrow is "later used" on. Then delete only the println! and confirm it compiles.
  1. Map the growth. Print len and capacity through 20 pushes on a Vec<u32>, then truncate(0), then shrink_to_fit, printing after each. Write down which of the numbers you observed are guaranteed by Vec's contract and which are the current implementation's choices.
  1. A row that survives short input. Build a Vec<Cell> from a whitespace-separated line of text, treating anything that parses as a number as Cell::Number and everything else as Cell::Text. Then print columns 0 through 4 using get, so a line with only three fields prints - for the missing two instead of panicking.