Lesson 2 · Unit 04
Hash maps and tuples
Values found by key, counting with entry, and values that travel in pairs
What you practise
HashMap,insert,getand theOptionit returns,entryfor counting, tuples and destructuring
Try a question from this lesson
Pick one
A HashMap stores pairs: a key and its value. insert adds a pair and get looks a key up. What do you expect this to print?
use std::collections::HashMap;
let mut stock = HashMap::new();
stock.insert("apples", 3);
stock.insert("pears", 7);
println!("{:?}", stock.get("pears"));Correct answer
Some(7)
Why
The key "pears" was stored with the value 7. As with a vector, get wraps what it finds in Some, because the key might not be there. The first line fetches HashMap from the collections that come with Rust.
The ideas
Concept cards are short on purpose. In the app they appear between questions, after you have met the idea.
Concept
Look up by key
A vector finds a value by its position. A HashMap finds it by a key that you choose: a name, a word, a number.
Each key appears once. Inserting it again replaces the value.
get answers Some(value) or None. That either-or answer is a type of its own, called Option.
use std::collections::HashMap;
let mut age = HashMap::new();
age.insert("Ada", 36);
age.insert("Ada", 37);
println!("{:?}", age.get("Ada"));
println!("{:?}", age.get("Bob"));
println!("{}", age.len());Concept
Counting with `entry`
The most common job for a map is counting.
count.entry(c).or_insert(0) finds the value for the key c. If the key is missing, it first puts 0 there. Either way you get a writing loan of the value.
The * in front means "the value itself", so += 1 adds one to it.
use std::collections::HashMap;
let mut count = HashMap::new();
for c in "hello".chars() {
*count.entry(c).or_insert(0) += 1;
}
println!("{:?}", count.get(&'l'));Concept
Tuples
A tuple groups a few values in round brackets. They may have different types: ("Ada", 36).
Take one part out by position with .0 or .1. Or unpack all the parts at once into new variables: let (name, age) = pair;.
A function can hand back a tuple, and so return two results.
let pair = ("Ada", 36);
println!("{} {}", pair.0, pair.1);
let (name, age) = pair;
println!("{name} is {age}");9 more exercises in the app
- 4× type the answer
- 2× fill the blanks
- 2× multiple choice
- 1× true or false
Bitpath is an iOS app in development. Join the waitlist and you get one email when it is ready to try.