Skip to content

Grow a List with Vec

The Course
•
26 min study

On Day 2 you looped over an array such as [15, 25, 20]. An array has a length fixed when you write the program, which works for a known set of values but not for a study log that grows every time you finish a session. A vector, written Vec<T>, is a list whose length can change while the program runs. T is the type of every item, so a Vec<u32> holds only u32 values.

vec![15, 25] creates a vector with two integers. push appends one item at the end. Because push changes the vector, the binding must be declared with let mut. The vector owns its items, just as a String owns its text, so the ownership rules from Day 3 apply to it: looping over the vector itself or passing it to a function moves it, and borrowing it with & does not.

Predict and run

Predict the number of sessions and the sum after the push.

Predict, then run Rust
fn main() {
    let mut durations = vec![15, 25];
    durations.push(20);
    let mut total = 0;
    for minutes in &durations {
        total += *minutes;
    }
    println!("{} sessions: {total} minutes", durations.len());
}
Check your prediction
Text
3 sessions: 60 minutes

for minutes in &durations borrows the vector for the length of the loop. Each minutes is a reference, a &i32 (no type is written, so Rust infers i32, as on Day 1) pointing at an item that still lives inside the vector, and *minutes reads the number it points to. When the loop ends the borrow ends, so durations.len() can still use the vector.

Replace &durations with durations and *minutes with minutes, then run. The loop now takes ownership of the vector and hands out each item by value. After the loop the vector is gone, and the compiler reports error[E0382]: borrow of moved value: durations at the len() call. Restore the borrow.

Start empty and read by position

A log often starts with nothing in it. Vec::new() creates an empty vector, but an empty vector gives Rust no item to infer the type from, so write the type on the binding: Vec<u32>. Positions, called indexes, start at 0, so the last item of a vector of length 3 is at index 2.

Fill an empty vector and index it Rust
fn main() {
    let mut log: Vec<u32> = Vec::new();
    println!("Before: {} sessions", log.len());
    log.push(30);
    log.push(45);
    log.push(10);
    println!("First: {} minutes", log[0]);
    println!("Last: {} minutes", log[log.len() - 1]);
    println!("All: {log:?}");
}
Text
Before: 0 sessions
First: 30 minutes
Last: 10 minutes
All: [30, 45, 10]

{log:?} uses debug formatting, which prints the whole vector in brackets. It is handy while you are learning, because it shows exactly what the vector contains.

Indexing trusts you to stay inside the vector. log[5] on a three-item vector compiles, but the program stops at run time with a panic: index out of bounds: the len is 3 but the index is 5. On Day 5 you will meet get, which returns a value you can check instead of crashing.

Change items in place

Sometimes you want to adjust every item, for example adding a five-minute break to each session. Borrow the vector mutably with &mut. Each minutes is then a &mut i32, and *minutes += 5 changes the item inside the vector.

Add a break to every session Rust
fn main() {
    let mut durations = vec![25, 40];
    for minutes in &mut durations {
        *minutes += 5;
    }
    println!("{durations:?}");
}
Text
[30, 45]

While the loop holds a borrow, the vector cannot be changed some other way. That rule from Day 3 stops a common mistake: changing the length of a vector while you loop over it.

Rust
fn main() {
    let mut durations = vec![25, 40];
    for minutes in &durations {
        if *minutes > 30 {
            durations.push(*minutes); // error
        }
    }
}

The compiler rejects this with error[E0502]: cannot borrow durations as mutable because it is also borrowed as immutable. push may need to move the items to a larger block of memory, which would leave the loop's reference pointing at nothing. Collect what you want to add in a second vector and push after the loop.

Pick the loop by what you need

Use &v to read every item, &mut v to change items in place, and plain v only when you are done with the vector and want to take each item for yourself.

Practice

Exercise

Your turn

Start with vec![8, 20], append 35 and count the entries at least 20 minutes long. Print 2 of 3 sessions qualify. Keep the vector available for the count of all sessions.

Your working space Rust
fn main() {
    let durations = vec![8, 20];
    println!("{durations:?}");
}
Hint 1: the idea

Borrow the vector in the loop so you can call len afterward.

Hint 2: a first step

Make the vector mutable and use push(35) before the loop. Inside the loop, compare *minutes >= 20.

Worked solution
Run the solution Rust
fn main() {
    let mut durations = vec![8, 20];
    durations.push(35);
    let mut qualifying = 0;
    for minutes in &durations {
        if *minutes >= 20 {
            qualifying += 1;
        }
    }
    println!("{qualifying} of {} sessions qualify", durations.len());
}
Text
2 of 3 sessions qualify

The 20-minute entry sits exactly on the boundary, and >= counts it. With > the answer would drop to 1, which is why boundary values are worth testing. The borrowed loop leaves the vector in main, so the final line can still use its length.

Was this article helpful?

Your response is saved on this device.