Skip to lesson content
navan✳THE BUILD LABRUST
0/53 complete
BUILD LAB / RUST/ COLLECTIONS THAT WORK
BUILD NOTE 21 / 53

Grow without guessing the final size.

Build, inspect, and mutate a growable sequence.

BY NAVAN SAMI◷ 7 MIN READFOUNDATIONSRUST 2024

01 Understand the contract

Vec<T> stores elements contiguously with a length and capacity. push adds an element, pop removes the final one, and get handles uncertain indexes. Capacity can exceed length and is not a promise that references remain valid forever. A growing vector may reallocate, which is why an active element reference can conflict with push. Borrow a slice when a function only needs to inspect elements, and consume into_iter when ownership of the elements should move into the loop.

02 Make it concrete

This is a complete standard-library example. Use Rust stable with the 2024 edition. Run it locally using the Rust workbench.

lessons/vectors/src/main.rs
fn main() {
    let mut queue = vec!["plan", "build"];
    queue.push("test");
    println!("last={:?}", queue.pop());
    for (index, task) in queue.iter().enumerate() {
        println!("{index}: {task}");
    }
}
↳ EXPECTED OUTPUT
last=Some("test")
0: plan
1: build
  1. 1

    push appends to the vector.

  2. 2

    pop returns Option because a vector may be empty.

  3. 3

    iter borrows each element and leaves the vector owned by main.

From the extracted rust-workbench folder
cargo run -p lesson_vectors

03 Mind the boundary

04 Your next build

A SMALL MISSION

Remove all negative readings using retain, preserving the remaining order.

Reveal one possible solution +
solutions/vectors/src/main.rs
fn main() {
    let mut readings = vec![-2, 4, -1, 0, 8];
    readings.retain(|n| *n >= 0);
    assert_eq!(readings, [4, 0, 8]);
}

05 Check your reasoning

QUICK SIGNAL CHECK

Which operation may invalidate references by reallocating a Vec?

ONE MORE CONTRACT YOU CAN EXPLAIN.

Understand it.
Then make it yours.

Run the example, try your own input, and explain the boundary. Log the lesson when the idea makes sense.

Built with curiosity. By Navan Sami. ↗Rust · Make the contract clear. Then build.