Lesson 08
Vectors and Slices
Goal
By the end of this lesson you will be able to:
-
Make a
Vec, empty or with values, and add items to it. -
Draw a
Vecin memory, and say what happens when it is full. -
Read one item by index, and change one item.
-
Step through a
Vecwithfor, reading or changing each item. -
Say what
let b = a;does to aVec, and when tocloneone. -
Write a function that accepts an array, a
Vecor a part of one, with&[T]. -
Explain why a reference into a
Vecstops you adding to it. -
Keep a list of
Stringvalues, and split a line into words.
A List That Grows
An array has its length in its type, and the length can never change. Most lists in a real program are not like that. The number of lines in a file, the number of names typed in, the number of marks in a class: none of these are known when the program is compiled. Vec, short for vector, is the list for that.
fn main() {
let mut marks: Vec<u32> = Vec::new();
marks.push(72);
marks.push(45);
marks.push(90);
println!("{marks:?}");
println!("{}", marks.len());
}
[72, 45, 90]
3
Vec::new() makes an empty list. push adds one item to the end, and needs the variable to be mut. Vec<u32> is the type: a list of u32 values. The type of the items goes between the angle brackets, and every item must have that type.
The type has to be written when the list starts empty, because the compiler cannot see what will go in it. Leave it out and the program does not compile.
error[E0282]: type annotations needed for `Vec<_>`
--> src/main.rs:2:9
|
2 | let marks = Vec::new();
| ^^^^^ ---------- type must be known at this point
When the values are known, vec! makes the list and fills it in one step, and the type is worked out from the values.
fn main() {
let marks = vec![72, 45, 90, 61, 38];
let names = vec![String::from("Asha"), String::from("Bo")];
let zeros = vec![0; 4];
println!("{marks:?}");
println!("{names:?}");
println!("{zeros:?}");
}
[72, 45, 90, 61, 38]
["Asha", "Bo"]
[0, 0, 0, 0]
vec! is written like an array with the word vec and an exclamation mark in front. vec![0; 4] is four zeros, the same shorthand as for an array.
A Vector in Memory
The items of a Vec live on the heap, because their number can change while the program runs. The variable itself holds the same three fields as a String: the address of the items, the length, and the capacity.
The length is how many items are in the list. The capacity is how many items the heap block has room for. Reserving a little more than is needed means the next push can go straight into the block. You can watch both numbers change.
fn main() {
let mut marks: Vec<u32> = Vec::new();
println!("length {} capacity {}", marks.len(), marks.capacity());
for mark in [72, 45, 90, 61, 38] {
marks.push(mark);
println!("length {} capacity {}", marks.len(), marks.capacity());
}
}
length 0 capacity 0
length 1 capacity 4
length 2 capacity 4
length 3 capacity 4
length 4 capacity 4
length 5 capacity 8
An empty list owns no heap memory. The first push reserves room for four items. The fifth push finds the block full, so it asks for a bigger block, copies every item across, and gives the old block back. The address in marks now points at the new block, and every item has a new address. The exact sizes are chosen by the standard library and may differ between versions.
pushCan Move Every ItemA
pushinto a full list moves all of the items to a new place in memory. Anything that remembered the old address would now point at memory that has been given back. Rust makes sure nothing does, and the rule that does it is explained below.
Reading and Changing Items
An item is read by index, the same as an array. The index counts from 0 and must be a usize.
fn main() {
let marks = vec![72, 45, 90];
println!("{}", marks[0]);
println!("{}", marks[marks.len() - 1]);
println!("{}", marks.is_empty());
}
72
90
false
marks[marks.len() - 1] is the last item. Ask for an index that does not exist and the program panics, the same as with an array.
thread 'main' (1310246) panicked at src/main.rs:4:25:
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
Changing a list needs mut. These are the methods you will use most.
fn main() {
let mut marks = vec![72, 45, 90];
marks[0] = 80;
println!("{marks:?}");
marks.insert(1, 55);
println!("{marks:?}");
let taken = marks.remove(2);
println!("took {taken}, left {marks:?}");
marks.sort();
println!("{marks:?}");
marks.reverse();
println!("{marks:?}");
println!("{}", marks.contains(&90));
marks.clear();
println!("{marks:?} {}", marks.len());
}
[80, 45, 90]
[80, 55, 45, 90]
took 45, left [80, 55, 90]
[55, 80, 90]
[90, 80, 55]
true
[] 0
| Method | What it does |
|---|---|
| v.push(x) | Add x at the end. |
| v.insert(i, x) | Put x at index i. Everything after it moves up one. |
| v.remove(i) | Take out the item at index i and give it back. |
| v.sort() | Put the items in order, smallest first. |
| v.reverse() | Turn the list round. |
| v.contains(&x) | true if x is in the list. Note the ampersand. |
| v.clear() | Remove every item. The heap block is kept. |
| v.len() | How many items. |
| v.is_empty() | true if there are none. |
contains takes a reference to the value it looks for, so the call is marks.contains(&90). The ampersand is easy to forget, and the compiler will tell you when you do.
Stepping Through a List
fn main() {
let mut marks = vec![72, 45, 90];
for mark in &marks {
println!("{mark}");
}
for mark in &mut marks {
*mark += 5;
}
println!("{marks:?}");
for (position, mark) in marks.iter().enumerate() {
println!("{position}: {mark}");
}
let total: u32 = marks.iter().sum();
println!("total {total}");
}
72
45
90
[77, 50, 95]
0: 77
1: 50
2: 95
total 222
for mark in &marks lends the list to the loop for reading. Each mark is a reference to one item. Printing reads through the reference on its own.
for mark in &mut marks lends the list with permission to change it. To change the item, you have to reach through the reference, and that is what the star in *mark += 5 does. mark is the address of the item. *mark is the item itself. Leave the star out and the compiler refuses, because you would be adding 5 to an address.
error[E0368]: binary assignment operation `+=` cannot be applied to type `&mut {integer}`
--> src/main.rs:5:9
|
5 | mark += 5;
| ----^^^^^
| |
| cannot use `+=` on type `&mut {integer}`
|
help: `+=` can be used on `{integer}` if you dereference the left-hand side
|
5 | *mark += 5;
| +
marks.iter().enumerate() pairs each item with its position, and marks.iter().sum() adds every item up. The type of total has to be written, because sum can add up into any number type and needs to be told which.
fn main() {
let marks = vec![72, 45, 90];
let mut largest = marks[0];
for mark in &marks {
if *mark > largest {
largest = *mark;
}
}
println!("{largest}");
}
90
Comparing and assigning want the value, not the address, so both lines write *mark.
Always Loop Over
&listor&mut list
for mark in marks, with no ampersand, hands the whole list to the loop. The loop uses it up, andmarkscannot be used again below the loop. Write&marksto read and&mut marksto change, and the list is still yours afterwards.
Ownership of a List
A Vec owns heap memory, so it follows the same rules as a String. Assigning it to another variable moves it.
fn main() {
let marks = vec![72, 45, 90];
let copy = marks;
println!("{copy:?}");
println!("{marks:?}");
}
error[E0382]: borrow of moved value: `marks`
--> src/main.rs:6:16
|
2 | let marks = vec![72, 45, 90];
| ----- move occurs because `marks` has type `Vec<i32>`, which does not implement the `Copy` trait
3 | let copy = marks;
| ----- value moved here
...
6 | println!("{marks:?}");
| ^^^^^ value borrowed here after move
|
help: consider cloning the value if the performance cost is acceptable
|
3 | let copy = marks.clone();
| ++++++++
Only the three stack fields were copied into copy, so both variables would point at the same heap block, and Rust does not allow two owners. marks stops working at the assignment. clone makes a second heap block with a copy of every item, and then both variables work. When the list goes out of scope, the heap block is given back, and every item in it is dropped with it.
Slices
A function that only reads a list should not ask for a Vec, and it should not ask for an array either, because then it accepts only that one kind. It should ask for a slice: &[u32] is a reference to a run of u32 values, wherever they live.
fn total(items: &[u32]) -> u32 {
let mut sum = 0;
for item in items {
sum += item;
}
sum
}
fn main() {
let fixed = [1, 2, 3];
let growing = vec![10, 20, 30, 40];
println!("{}", total(&fixed));
println!("{}", total(&growing));
println!("{}", total(&growing[1..3]));
}
6
100
50
One function accepts an array, a Vec, and a part of a Vec. &growing[1..3] is the items at index 1 and 2, and the end of the range is not included. A slice holds an address and a length, the same two fields as a &str, and nothing is copied when one is made.
Ask for &Vec<u32> instead and the array is refused.
error[E0308]: mismatched types
--> src/main.rs:11:26
|
11 | println!("{}", total(&fixed));
| ----- ^^^^^^ expected `&Vec<u32>`, found `&[{integer}; 3]`
`&[T
for Lists,&strfor Text\] The rule is the same in both cases. A parameter that only reads should be a slice.&straccepts a literal, aStringor part of one.&[T]accepts an array, aVec` or part of one. Ask for the owned type only when the function keeps the value.
A Reference Into a List That Grows
fn main() {
let mut marks = vec![72, 45, 90];
let first = &marks[0];
marks.push(61);
println!("{first}");
}
error[E0502]: cannot borrow `marks` as mutable because it is also borrowed as immutable
--> src/main.rs:5:5
|
4 | let first = &marks[0];
| ----- immutable borrow occurs here
5 | marks.push(61);
| ^^^^^^^^^^^^^^ mutable borrow occurs here
6 |
7 | println!("{first}");
| ----- immutable borrow later used here
This program looks harmless, and it is the one the picture of the full list was drawn for. first holds the address of the first item. push may find the block full, move every item to a new block, and give the old one back. first would then point at memory that no longer belongs to the list, and the last line would print whatever happens to be there now.
Rust does not need to know whether the block is full. first is a reference that reads the list, push needs a reference that changes it, and the two cannot be alive at the same time. The program is refused before it runs.
Use the reference before the push and the borrow is over, so the program compiles.
fn main() {
let mut marks = vec![72, 45, 90];
let first = &marks[0];
println!("{first}");
marks.push(61);
println!("{marks:?}");
}
72
[72, 45, 90, 61]
A List of Text
A Vec can hold any type, as long as every item has the same one. A list of names is a Vec<String>.
fn main() {
let mut names: Vec<String> = Vec::new();
names.push(String::from("Asha"));
names.push(String::from("Bo"));
names.push("Chen".to_string());
for name in &names {
println!("{name} has {} letters", name.len());
}
}
Asha has 4 letters
Bo has 2 letters
Chen has 4 letters
Each String owns its own text on the heap, and the list owns the String values. When the list goes out of scope, every name is dropped with it.
The Words of a Line
split_whitespace hands out the words of a line one at a time. collect gathers everything it hands out into a list.
fn main() {
let line = "the quick brown fox";
let words: Vec<&str> = line.split_whitespace().collect();
println!("{words:?}");
println!("{}", words.len());
println!("{}", words[1]);
}
["the", "quick", "brown", "fox"]
4
quick
Each word is a &str that looks into line, with nothing copied. Vec<&str> has to be written, because collect can build several kinds of collection.
Everything Together
This program reads whole numbers from the keyboard, one per line, until the user types an empty line. Then it reports on them.
use std::io;
fn main() {
let mut numbers: Vec<i32> = Vec::new();
println!("Type one whole number per line. Type an empty line to stop.");
loop {
let mut line = String::new();
io::stdin().read_line(&mut line).expect("could not read the line");
let text = line.trim();
if text.is_empty() {
break;
}
let number: i32 = text.parse().expect("that was not a whole number");
numbers.push(number);
}
if numbers.is_empty() {
println!("no numbers");
return;
}
let mut total = 0;
let mut smallest = numbers[0];
let mut largest = numbers[0];
for n in &numbers {
total += n;
if *n < smallest {
smallest = *n;
}
if *n > largest {
largest = *n;
}
}
numbers.sort();
println!("{} numbers: {numbers:?}", numbers.len());
println!("total {total}, smallest {smallest}, largest {largest}");
println!("average {:.2}", total as f64 / numbers.len() as f64);
}
Type one whole number per line. Type an empty line to stop.
5
3
9
1
4 numbers: [1, 3, 5, 9]
total 18, smallest 1, largest 9
average 4.50
Four parts of this program need extra explanation.
-
A new
Stringis made on every pass of the loop, so each line is read into empty text. Made once outside the loop, the lines would pile up in it. -
returninmainends the program. Everything after it is skipped when the list is empty, which also keepsnumbers[0]from being read on an empty list. -
total += nadds through the reference on its own, while the two comparisons and the two assignments need*n, the value itself. -
numbers.sort()changes the list in place, which is whynumbersismut, and the sorted list is what{:?}prints.
Reference
| Written as | What it does |
|---|---|
| Vec::new() | An empty list. Write its type on the variable. |
| vec![1, 2, 3] | A list with values. Its type is Vec<i32>. |
| v.push(x) | Add x at the end. Needs mut. |
| v[0] | The first item. Panics if the list is empty. |
| v[i] = x | Change one item. Needs mut. |
| v.len() v.is_empty() | How many items; whether there are none. |
| v.insert(i, x) | Put x at index i. |
| v.remove(i) | Take the item at index i out. |
| v.sort() v.reverse() | Order the items; turn the list round. |
| v.contains(&x) | true if x is in the list. |
| for x in &v | Step through, reading each item. |
| for x in &mut v | Step through, changing each item with *x. |
| v.iter().enumerate() | Pair each item with its index. |
| v.iter().sum() | Add every item up. Needs a type on the variable. |
| let w = v.clone(); | A second list with a copy of every item. |
| fn f(items: &[u32]) | Accepts an array, a Vec or a part of one. |
| &v[1..3] | A slice of the items at index 1 and 2. |
| s.split_whitespace().collect() | The words of a line as a Vec<&str>. |
Check what stuck
The practice sheet for this lesson has 50 multiple-choice questions. Each one is a short program: pick what it prints, or why it does not compile.
Start practice →