Grow without guessing the final size.
Build, inspect, and mutate a growable sequence.
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.
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}");
}
}last=Some("test")
0: plan
1: build- 1
push appends to the vector.
- 2
pop returns Option because a vector may be empty.
- 3
iter borrows each element and leaves the vector owned by main.
cargo run -p lesson_vectors03 Mind the boundary
04 Your next build
Remove all negative readings using retain, preserving the remaining order.
Reveal one possible solution +
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
Which operation may invalidate references by reallocating a Vec?
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.