Learn/Rust/7. Collections
Lesson 7 of 15
Sign in

Rust, lesson 7

Collections

To hold a list of scores or a table of prices you need a collection. Rust's standard library offers several; the two you will use most are Vec (a growable list) and HashMap (lookup by key). Fixed-size arrays round out the set.

Arrays

An array has a fixed length that is part of its type: [i32; 3] holds exactly three i32s.

let podium = ["Ana", "Ben", "Cy"];
let zeros = [0; 5];               // [0, 0, 0, 0, 0]
println!("{} {}", podium.len(), podium[0]); // 3 Ana

Indexing past the end, such as podium[3], stops the program with a panic instead of reading random memory. That check is part of Rust's safety promise.

Vectors

A Vec<T> is a growable list of values of type T. The vec! macro creates one with starting values:

The vector must be mut to add or remove items. {:?} prints a whole collection in debug form: println!("{scores:?}") shows [70, 85, 92].

Safe access with get

scores[10] panics if there is no item 10. scores.get(10) instead returns an Option: Some(&value) when the index exists, None when it does not. You will see Option everywhere in Rust; it is how the language says "maybe there is no value" without null.

Looping over a vector

Note the & in for s in &scores: it loops over the vector by reference, so scores is still usable afterwards. Without it, the loop would consume the vector. To change items in place, loop with &mut scores and write through the reference: *s += 5.

Handy methods: contains(&x), iter().sum::<i32>(), iter().max(), sort(), reverse(), join(" ") (on a vector of strings).

Hash maps

HashMap<K, V> maps keys to values. Bring it into scope with use:

get returns an Option, because the key might be missing. if let is a short form of match for when you care about only one pattern.

The entry API makes counting easy. entry(key).or_insert(0) returns a mutable reference to the value, inserting 0 first if the key is new:

The * follows the reference to the number so you can add to it.

Iterating a HashMap visits entries in an unpredictable order. When order matters, keep a separate Vec of keys, sort the keys, or use BTreeMap, which keeps keys sorted (lesson 13).

Further reading

  • The Rust Book: Storing lists of values with vectors
  • The Rust Book: Storing keys with associated values in hash maps
  • std::vec::Vec

2 exercises to try what you just read.

Exercise 1

Above average

The first number is a count n, followed by n test scores. Print the average with one decimal, then on the next line every score strictly above the average, in the original order, separated by spaces. If none is above, print none.

Sample input:

Sample output:

Press Ctrl Enter or Check to test your code.

Exercise 2

Vote counter

Each input line holds one vote: a candidate's name. Count the votes and print each candidate with their total, in the order each name first appeared, as name: count.

Sample input:

Sample output:

Press Ctrl Enter or Check to test your code.

let mut scores = vec![70, 85, 92];
scores.push(60);                     // [70, 85, 92, 60]
let last = scores.pop();             // Some(60), scores is [70, 85, 92]
println!("{} {}", scores.len(), scores[1]); // 3 85
let empty: Vec<String> = Vec::new();
match scores.get(10) {
    Some(s) => println!("found {s}"),
    None => println!("no score there"),
}
for s in &scores {
    println!("{s}");
}
for (i, s) in scores.iter().enumerate() {
    println!("{i}: {s}");
}
use std::collections::HashMap;

let mut stock: HashMap<String, u32> = HashMap::new();
stock.insert("apple".to_string(), 5);
stock.insert("pear".to_string(), 2);

if let Some(qty) = stock.get("apple") {
    println!("apples: {qty}");
}
stock.remove("pear");
println!("{}", stock.contains_key("pear")); // false
let mut counts = HashMap::new();
for word in ["kiwi", "fig", "kiwi"] {
    *counts.entry(word).or_insert(0) += 1;
}
5
70 85 92 60 78
77.0
85 92 78
kiwi
mango
kiwi
fig
kiwi
mango
kiwi: 3
mango: 2
fig: 1