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.”
Practice
Section titled “Practice”1. Collect the even numbers
Section titled “1. Collect the even numbers”Start with an empty vector. Loop over the numbers 1 to 10 and push only the even ones. Then print the vector and how many items it has. Hint: a number n is even when n % 2 == 0.
Show solution
fn main() { let mut evens = Vec::new();
for n in 1..=10 { if n % 2 == 0 { evens.push(n); } }
println!("{:?}", evens); println!("Found {} even numbers", evens.len());}Output:
[2, 4, 6, 8, 10]Found 5 even numbersNotice we never wrote the type. Rust sees the push(n) calls and works out that evens is a Vec<i32>.
2. A stack of plates
Section titled “2. A stack of plates”Push three plates onto a vector: "blue", "green", then "red". Take two plates off the top with .pop() and print each one. Finally, print what’s left. Hint: .pop() returns an Option, so print it with {:?}.
Show solution
fn main() { let mut plates = Vec::new(); plates.push("blue"); plates.push("green"); plates.push("red");
println!("Took {:?}", plates.pop()); println!("Took {:?}", plates.pop()); println!("Left: {:?}", plates);}Output:
Took Some("red")Took Some("green")Left: ["blue"]pop() always takes the last item you pushed, like taking the top plate off a stack. It returns Some(...), not the plain value, because the vector might be empty. Then you’d get None instead of a crash.
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
Read more
Section titled “Read more”- Storing Lists of Values with Vectors — The Rust Book: creating, reading and updating vectors, and why you can’t push while holding a reference.
- Vectors — Rust by Example: one runnable example that shows the most common
Vecoperations. Vec— standard library docs: the full list of methods, such asinsert,retain,extendandcontains.- The
vec!macro — standard library docs: every form ofvec!, includingvec![0; 10]for repeated values.