Rust Vectors
A vector, written Vec<T>, is a growable list of values of type T. Like an array, its elements sit side by side in memory, but a vector stores them on the heap, so it can grow or shrink while the program runs. It is the collection you will reach for most often in Rust.
Creating a vector
There are two common ways:
fn main() {
let mut names: Vec<String> = Vec::new(); // empty, type written out
names.push(String::from("Ana"));
let primes = vec![2, 3, 5, 7, 11]; // vec! macro with initial values
let blanks = vec![' '; 3]; // three spaces
println!("{:?}", names);
println!("{:?}", primes);
println!("{:?}", blanks);
}["Ana"]
[2, 3, 5, 7, 11]
[' ', ' ', ' ']
The vec! macro is the shortcut for "make a vector holding these values". An empty Vec::new() often needs a type annotation, unless a later push tells the compiler the element type.
Adding and removing elements
| Method | Effect |
|---|---|
push(x) |
add x to the end |
pop() |
remove the last element, returns Option<T> |
insert(i, x) |
put x at index i, shifting the rest right |
remove(i) |
take out the element at i, shifting the rest left |
clear() |
remove everything |
len() / is_empty() |
how many elements / are there none? |
All methods that change the vector need it to be declared mut.
fn main() {
let mut queue = vec!["Ben", "Cleo"];
queue.push("Dan"); // Dan joins the end
queue.insert(0, "Amy"); // Amy cuts in at the front
println!("Queue: {:?}", queue);
let served = queue.remove(0); // first in line is served
println!("Served: {}", served);
let last = queue.pop(); // last person leaves
println!("Left the line: {:?}", last);
println!("Queue: {:?} (length {})", queue, queue.len());
}Queue: ["Amy", "Ben", "Cleo", "Dan"]
Served: Amy
Left the line: Some("Dan")
Queue: ["Ben", "Cleo"] (length 2)
pop returns Some(value) because the vector might be empty — in that case it returns None instead of crashing.
Reading elements
Use v[i] when you are sure the index exists, or v.get(i) when it might not. Indexing past the end panics; get returns None.
fn main() {
let colors = vec!["red", "green", "blue"];
println!("Second color: {}", colors[1]);
if let Some(c) = colors.get(5) {
println!("Sixth color: {}", c);
} else {
println!("There is no sixth color");
}
println!("Has green? {}", colors.contains(&"green"));
}Second color: green
There is no sixth color
Has green? true
Looping and modifying in place
Loop over &v to read each element, or over &mut v to change each element. The * in *n means "the value this reference points to".
fn main() {
let mut prices = vec![10, 25, 40];
for n in &mut prices {
*n += 5; // add a 5 unit fee to every price
}
for (i, n) in prices.iter().enumerate() {
println!("Item {}: {}", i, n);
}
let total: i32 = prices.iter().sum();
println!("Total: {}", total);
}Item 0: 15
Item 1: 30
Item 2: 45
Total: 90
Sorting, filtering and more
Vectors share all the slice methods you saw with arrays — sort, reverse, contains, first, last — plus a few extras.
fn main() {
let mut words = vec!["pear", "fig", "apple", "fig", "kiwi"];
words.sort();
println!("Sorted: {:?}", words);
words.dedup(); // remove consecutive duplicates
println!("Unique: {:?}", words);
words.retain(|w| w.len() > 3); // keep only longer words
println!("Long: {:?}", words);
let mut more = vec!["plum", "lime"];
words.append(&mut more); // move all of `more` into `words`
println!("Joined: {:?}", words);
}Sorted: ["apple", "fig", "fig", "kiwi", "pear"]
Unique: ["apple", "fig", "kiwi", "pear"]
Long: ["apple", "kiwi", "pear"]
Joined: ["apple", "kiwi", "pear", "plum", "lime"]
retain takes a closure — a small inline function |w| ... that decides whether to keep each element. Closures get their own lesson later.
Vectors and ownership
A vector owns its elements. Passing a vector by value moves it, so the original variable can no longer be used. To let a function read it, pass a slice &v (type &[T]); to let it change the vector, pass &mut v.
fn show(v: Vec<i32>) { println!("{:?}", v); }
fn main() {
let v = vec![1, 2, 3];
show(v);
println!("{:?}", v); // error: v was moved into show
}error[E0382]: borrow of moved value: `v`Tip: Write function parameters as
&[T]rather than&Vec<T>. A slice works for both vectors and arrays.
Test yourself
What does pop() return when the vector is empty?
- 0
- It panics
- None
- An empty string
Which macro creates a vector with initial values?
- vector![]
- vec![]
- Vec![]
- list![]
After let mut v = vec![1, 2, 3]; v.insert(1, 9); what is v?
- [9, 1, 2, 3]
- [1, 9, 2, 3]
- [1, 2, 9, 3]
- [1, 9, 3]