Vec Basics
Vec is a list that can grow or shrink as you add or remove things from it.Creating a Vec
A Vec is created either with Vec::new() for an empty list or the vec! macro to list initial elements directly.
Example: Creating a Vec
fn main() {
let numbers = vec![1, 2, 3];
println!("{:?}", numbers);
}
Login to try C/C++/Java/PHP code in the editor
Pushing and Popping
.push() appends an element to the end of a mutable Vec, and .pop() removes and returns the last element, wrapped in an Option since the vector could be empty.
Example: Pushing and Popping
fn main() {
let mut stack = Vec::new();
stack.push(10);
stack.push(20);
let last = stack.pop();
println!("Popped: {:?}, remaining: {:?}", last, stack);
}
Login to try C/C++/Java/PHP code in the editor
Accessing Elements Safely
Direct indexing with [] panics if the index is out of bounds. .get(index) instead returns an Option, letting you handle a missing index without crashing.
Example: Accessing Elements Safely
fn main() {
let items = vec!["a", "b", "c"];
println!("{:?}", items.get(1));
println!("{:?}", items.get(10));
}
Login to try C/C++/Java/PHP code in the editor
Iterating Over a Vec
A for loop can iterate directly over a Vec's elements by reference, letting you process each item without taking ownership of the whole vector.
Example: Iterating Over a Vec
fn main() {
let scores = vec![90, 85, 77];
for score in &scores {
println!("Score: {}", score);
}
}
Login to try C/C++/Java/PHP code in the editor
- Trying to index past the end of a
Vec, which panics at runtime instead of returning a default value. - Forgetting
Vec::new()needsmuton the binding before you can push new elements onto it. - Using
vec[i]when the index might be out of bounds, instead of the safer.get(i)which returns anOption.
Vec<T>is a growable, heap-allocated list of elements of typeT.vec![...]is a convenient macro for creating aVecwith initial elements..push()adds an element to the end;.pop()removes and returns the last one.- Indexing with
[]panics on an out-of-bounds index, while.get()returnsOptionsafely.
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: