Skip to content

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.

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.

▶ Try it Yourself

You can also start empty and build it up:

let mut numbers: Vec<i32> = Vec::new();

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]
▶ Try it Yourself

Same square-bracket syntax as arrays:

fn main() {
let fruits = vec!["apple", "banana", "cherry"];
println!("{}", fruits[0]);
println!("Length: {}", fruits.len());
}
▶ Try it Yourself

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"),
}
}
▶ Try it Yourself
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);
}
▶ Try it Yourself
fn main() {
let numbers = vec![10, 20, 30];
for n in &numbers {
println!("{n}");
}
}
▶ Try it Yourself

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.

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 with vec![...] or Vec::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 an Option instead, which won’t panic.
  • Loop with for item in &vec to borrow items instead of consuming the vector.