Grow a Vec
Quick answer
Use Vec<T> when the number of items can change while the program runs. A vector owns its elements and keeps them in a contiguous sequence.
Length and capacity
vec! creates a vector with initial elements. push adds to the end and pop removes the last element, returning an Option. Length counts elements; capacity is the number of elements that can fit without reallocating. For nonzero-sized elements, growing past capacity can move the backing allocation.
fn main() { let mut tasks = vec!["read"]; tasks.push("write"); println!("{:?}", tasks.pop()); println!("{:?}", tasks);}Expected stdout (not executed):
Some("write")["read"]The last inserted task is removed.
fn main() { let mut scores = Vec::with_capacity(4); scores.push(12); println!("length: {}, room: {}", scores.len(), scores.capacity() >= 4);}Expected stdout (not executed):
length: 1, room: trueCapacity is at least four, but only one element exists.
Common mistake
Capacity does not initialize elements; indexing an empty reserved vector still panics.
Try it yourself
Create an empty vector, push three numbers, pop twice and explain the final length.
Static examples for Rust 1.85.0, edition 2024. Run them locally in a disposable project; ByteMind execution support and these outputs have not been verified.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Grow a Vec — practice quiz
Choose one answer per question, then review the explanation.
What does `vec![4, 8].pop()` return?
A vector has length 3 and capacity 8. How many elements are currently stored?
What can happen when a nonempty Vec grows beyond its capacity?