Vectors
A Vec<T> is a growable list of values of the same type, allocated on the heap. The vec! macro is the usual way to create one with initial values.
main.rs
Try it yourself →fn main() {
let numbers = vec![1, 2, 3, 4, 5];
println!("{:?}", numbers);
let sum: i32 = numbers.iter().sum();
println!("sum = {}", sum);
}Output
[1, 2, 3, 4, 5] sum = 15
Growing and shrinking a vector
push adds an item to the end; remove takes an item out by index and returns it, shifting everything after it down. Both require the vector itself to be mutable.
main.rs
Try it yourself →fn main() {
let mut fruits = vec!["apple", "banana", "cherry"];
fruits.push("date");
println!("{:?}", fruits);
let first = fruits.remove(0);
println!("removed: {}", first);
println!("{:?}", fruits);
}Output
["apple", "banana", "cherry", "date"] removed: apple ["banana", "cherry", "date"]
Next: iterators and closures — transforming a collection without writing a manual loop.
Practice exercise
Given a vector numbers: Vec<i32> = vec![4, 8, 15, 16], use .iter().max() to find the largest value and print it (it returns an Option<&i32>, so unwrap it).