Rust, lesson 7
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.
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 AnaIndexing 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.
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].
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.
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).
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).
2 exercises to try what you just read.
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")); // falselet mut counts = HashMap::new();
for word in ["kiwi", "fig", "kiwi"] {
*counts.entry(word).or_insert(0) += 1;
}5
70 85 92 60 7877.0
85 92 78kiwi
mango
kiwi
fig
kiwi
mangokiwi: 3
mango: 2
fig: 1