The number of orders at Rusdi's Pancake Stall is never fixed. In the morning there are two, by evening there can be thirty. The array from the data types lesson doesn't fit, because its number of items is fixed from the start. Instead, Rust has Vec<T> (read vector): a list whose length can grow and shrink while the program runs. Every item has the same type: the T in the angle brackets. For example, Vec<u32> is a list of u32 numbers.
In the kitchen, a Vec is like the order spike, a metal spike that holds the order notes. Each new order note goes onto the end, the note at the end can be taken off again, and the count changes all day. In code, the spike is the Vec and each note is one item. The menu price board is different: it is printed once with exactly three prices. The price board is like an array ([u32; 3], a fixed number of items), and the order spike is like a Vec<u32>.
Making a Vec and adding items
This program makes an empty Vec and adds three orders, then makes a second Vec that already holds three prices:
fn main() {
let mut orders: Vec<u32> = Vec::new();
orders.push(102);
orders.push(70);
orders.push(38);
println!("{:?}", orders);
println!("Order count: {}", orders.len());
let prices = vec![32, 38, 5];
println!("{:?}", prices);
}
The output:
[102, 70, 38]
Order count: 3
[32, 38, 5]
Vec::new()makes an empty Vec. Its item type is written inVec<u32>, because from an empty Vec the compiler can't guess it yet..push(value)adds one item at the end, like a new note on the spike. Because the contents change, the variable must belet mut.vec makes a Vec that is filled right away. The item type is guessed from the values..len()gives the number of items.{:?}prints all the items in square brackets. A plain{}can't print a Vec.
If the mut is missing, push is refused:
error[E0596]: cannot borrow `orders` as mutable, as it is not declared as mutable
--> src/main.rs:3:5
|
3 | orders.push(102);
| ^^^^^^ cannot borrow as mutable
|
help: consider changing this to be mutable
|
2 | let mut orders: Vec<u32> = Vec::new();
| +++
push needs to change orders. The compiler calls this borrowing orders as mutable (allowed to change). That is allowed only for a mut variable, and the help part shows where to add mut. Borrowing is covered in the Borrowing lesson.
Reading items: [i] or .get(i)
A Vec's items are numbered from 0, just like an array. In error messages, this position number is called the index. There are two ways to read an item: orders[i] and orders.get(i). The last line of this program reads orders[3] on purpose, though there are only three orders. Before you look at the output, guess: does it compile? If so, what does that line print?
fn main() {
let orders = vec![102, 70, 38];
println!("{}", orders[0]);
println!("{:?}", orders.get(1));
println!("{:?}", orders.get(3));
println!("{}", orders[3]);
}
$ cargo run
Compiling stall v0.1.0 (/home/you/stall)
Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.16s
Running `target/debug/stall`
102
Some(70)
None
thread 'main' (23382854) panicked at src/main.rs:6:26:
index out of bounds: the len is 3 but the index is 3
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
orders[0]gives the item directly:102.orders.get(1)givesSome(70): the item is there.orders.get(3)givesNone: number 3 doesn't exist, and the program keeps running. ThisSomeandNoneis theOptionyou saw briefly in the match lesson.orders[3]compiles, because a Vec's length is only known while the program runs. When it runs, the program panics (stops) withindex out of bounds: the len is 3 but the index is 3. The items are only numbers 0, 1 and 2. So that line prints no number at all.- Use
[i]when the number is certain to exist. Use.get(i)(thenmatch) when the number might be out of range, for example when it comes from a customer's input.
push, pop, sort and sum
This program changes orders a few times. Then it adds up and prints the items:
fn main() {
let mut orders = vec![102, 70, 38];
orders.push(45);
println!("{:?} len {}", orders, orders.len());
let last = orders.pop();
println!("{:?}", last);
orders.sort();
println!("{:?}", orders);
let total: u32 = orders.iter().sum();
println!("Total today: {}", total);
for p in &orders {
println!("Order: {}", p);
}
}
The output:
[102, 70, 38, 45] len 4
Some(45)
[38, 70, 102]
Total today: 210
Order: 38
Order: 70
Order: 102
This table shows what orders holds after each step:
| Step | orders afterwards |
len() |
|---|---|---|
vec![102, 70, 38] |
[102, 70, 38] |
3 |
push(45) |
[102, 70, 38, 45] |
4 |
pop(), result Some(45) |
[102, 70, 38] |
3 |
sort() |
[38, 70, 102] |
3 |
.pop()takes off the item at the end and hands it over asSome(...). From an empty Vec the result isNone..sort()sorts the items from small to large, in the Vec itself, so it needsmuttoo..iter().sum()adds up every item:.iter()takes the items one by one, then.sum()adds them up. The result type must be written:let total: u32.for p in &ordersborrows each item, soorderscan still be used afterwards.
Slices: part of a Vec
This program takes only items 1 and 2, then adds them up:
fn main() {
let orders = vec![102, 70, 38, 45];
let middle = &orders[1..3];
println!("{:?}", middle);
let total: u32 = middle.iter().sum();
println!("{}", total);
}
The output is [70, 38], then 108. &orders[1..3] is a slice (a piece): a borrow of part of the items, from number 1 up to before 3, just like a range in for. Its type is &[u32]. Nothing is copied: the slice only points at the original Vec's items.
A Vec of Strings and ownership
A Vec can hold String text too. The difference from numbers: push moves the String into the Vec. This program uses note again after the push, and the compiler refuses it:
fn main() {
let mut queue: Vec<String> = Vec::new();
let note = String::from("Egg Pancake");
queue.push(note);
println!("{}", note);
}
error[E0382]: borrow of moved value: `note`
--> src/main.rs:5:20
|
3 | let note = String::from("Egg Pancake");
| ---- move occurs because `note` has type `String`, which does not implement the `Copy` trait
4 | queue.push(note);
| ---- value moved here
5 | println!("{}", note);
| ^^^^ value borrowed here after move
|
help: consider cloning the value if the performance cost is acceptable
|
4 | queue.push(note.clone());
| ++++++++
borrow of moved value means the code uses a value that was already moved, as in the loop lesson. The note now belongs to queue. Read it through the Vec, queue[0], or push a copy with note.clone() if note is still needed. The rules about who owns a value are called ownership, and they are covered fully in the Ownership lesson.
📌 Capacity
A Vec reserves more room in memory than it uses. With that spare room, push doesn't have to move every time. The Vec moves to a bigger place, taking all its items with it, only when its room is full. len() is the number of items in use, capacity() the room already reserved. Vec::with_capacity(100) reserves room for 100 items from the start: len() 0, capacity() 100. This is useful when you roughly know how many items there will be.
⚠️ What makes a Vec get refused or panic
- Forgetting
mut.push,popandsortare refused withcannot borrow ... as mutable. - A number out of range.
v[i]panics at runtime. When the number isn't certain, usev.get(i). - Printing a Vec with
{}. Refused with`Vec<{integer}>` doesn't implement `std::fmt::Display`: a Vec can't be printed with{}. Use{:?}. sum()without a type.let total = orders.iter().sum();is refused withtype annotations needed. Writelet total: u32.- Using a String after pushing it. The String has moved into the Vec.
TL;DR: Vec<T> is a list whose length can change while the program runs, and every item has the type T. Make it with Vec::new() or vec![...], and write let mut when its contents change. push adds an item at the end, pop takes one off the end (Some(x), or None when it is empty), sort sorts, len counts the items, and iter().sum() adds them up (write the result type). Items are numbered from 0: v[i] reads item number i of the Vec v. When the number is out of range, v[i] panics (the program stops) with index out of bounds: the len is 3 but the index is 3. v.get(i) gives Some when the item is there, or None when it isn't. Print with {:?}. &v[1..3] is a slice, a borrow of items 1 and 2 without copying them. push moves a String into the Vec, so its old variable can't be used again.
⚡ A list that can grow
Write:
let mut orders: Vec<u32> = Vec::new();
orders.push(102);
orders.push(70);
println!("{:?}", orders);
Meaning: Vec<T> is a list whose length can change, and every item has the type T, here u32. Vec::new() makes an empty Vec, and push adds one item at the end. Because the contents change, the variable must be let mut. Print the items with {:?}, not {}.
⚡ [i] or .get(i)
Guess first: orders holds only 3 orders, numbered 0 to 2. Does orders[3] compile?
It does, because a Vec's length is only known while the program runs. When it runs, the program panics (stops) with index out of bounds: the len is 3 but the index is 3.
Meaning: v[i] reads the item at number i of the Vec v, and panics when the number is out of range. v.get(i) is safer: it gives Some(...) when the item is there, None when it isn't.
⚡ pop, sort and sum
Write:
let last = orders.pop();
orders.sort();
let total: u32 = orders.iter().sum();
Meaning: pop takes off the item at the end and hands it over as Some(...), sort sorts the items from small to large, and iter().sum() adds them all up. The result type of sum must be written. pop and sort change the Vec, so orders must be let mut.