Rust Vectors
A vector (Vec) is like an array, but it can grow and shrink at runtime. In everyday Rust code, when you need a list of things, you’ll reach for a Vec far more often than a fixed-size array.
Creating a vector
Section titled “Creating a vector”fn main() { let numbers: Vec<i32> = vec![1, 2, 3]; println!("{:?}", numbers);}vec![] is a macro (notice the !) that builds a Vec from a list of values, similar to how you’d write an array literal.
You can also start empty and build it up:
let mut numbers: Vec<i32> = Vec::new();Adding elements
Section titled “Adding elements”Use .push() to add to the end. The vector needs to be mut since you’re changing it:
fn main() { let mut numbers = Vec::new();
numbers.push(1); numbers.push(2); numbers.push(3);
println!("{:?}", numbers);}Output:
[1, 2, 3]Accessing elements
Section titled “Accessing elements”Same square-bracket syntax as arrays:
fn main() { let fruits = vec!["apple", "banana", "cherry"];
println!("{}", fruits[0]); println!("Length: {}", fruits.len());}For a safer lookup that doesn’t panic on a bad index, use .get(), which hands back an Option instead (more on that on the Option page):
fn main() { let fruits = vec!["apple", "banana", "cherry"];
match fruits.get(10) { Some(fruit) => println!("Found: {fruit}"), None => println!("No fruit at that index"), }}Removing elements
Section titled “Removing elements”fn main() { let mut numbers = vec![1, 2, 3, 4, 5];
numbers.pop(); // removes the last item -> [1, 2, 3, 4] numbers.remove(0); // removes by index -> [2, 3, 4]
println!("{:?}", numbers);}Looping over a vector
Section titled “Looping over a vector”fn main() { let numbers = vec![10, 20, 30];
for n in &numbers { println!("{n}"); }}Notice the & before numbers — looping with for n in &numbers borrows each item instead of taking ownership of the vector. Leave off the & and the vector gets moved into the loop, meaning you can’t use numbers afterward. Borrowing is what you want almost all of the time.
A quick word on generics
Section titled “A quick word on generics”You’ll notice the type is written Vec<i32> — the <i32> part says “a vector of i32 values.” This bracket notation is called a generic, and you’ll see it again properly on the Generics page. For now, just read Vec<T> as “a vector holding values of type T.”
Vec<T>is a growable list; create one withvec![...]orVec::new()..push()adds to the end;.pop()removes the last item;.remove(i)removes by index.vec[i]panics on a bad index;.get(i)returns anOptioninstead, which won’t panic.- Loop with
for item in &vecto borrow items instead of consuming the vector.
Quick check
Section titled “Quick check”Quick check
1. What happens when you index a Vec with a bad index, like numbers[10]?
2. Which method lets you look up an index without risking a panic?
3. What does the & in `for n in &numbers` do?
Score: 0 / 3