HashMaps and Errors
Programming Languages · Rust Data · 14 min
Look values up by key with HashMap, and handle things that can fail with Result.
HashMap: look things up by key
A HashMap stores pairs: a key and its value, like words and their meanings in a dictionary. It lives in the standard library, so bring it in with use at the top.
let mut ages: HashMap<&str, u32> = HashMap::new();
ages.insert("Ada", 36);
<&str, u32> means: keys are text, values are numbers.
Insert
"apple"with price3and"bread"with price2.Print
2 itemsusingprices.len().
get gives you an Option
.get(key) looks up a key. The key might not be there, so it returns an Option: Some(value) or None. You already know how to handle that:
if let Some(age) = ages.get("Ada") {
println!("Ada is {}", age);
}
Use
if letwithprices.get("apple")to printapple costs 3.Use
matchonprices.get("cake"): print the price forSome, andNo cake todayforNone.
Counting with entry
To count things, use entry. It finds a key's value, adding a starting value first if the key is new:
*counts.entry(word).or_insert(0) += 1;
Read it as: "find the count for this word (start at 0), then add 1". The * means "the value itself", not the borrow.
counts["cat"] reads a value directly (it panics if the key is missing).
Loop over
wordsand count each one withentryandor_insert(0).Print
cat: 3and thendog: 1, reading the numbers fromcounts.
Result: Ok or Err
Some things can fail. Turning text into a number fails if the text is "abc". So parse returns a Result: Ok(value) when it worked, or Err(error) when it didn't. Handle both with match:
match "42".parse::<i32>() {
Ok(n) => println!("Got {}", n),
Err(_) => println!("Oops"),
}
::<i32> says which kind of number you want.
Write
fn check(text: &str)that parsestextas ani32. OnOk(n)printDouble:andn * 2. OnErrprintNot a number.Call
check("123"), thencheck("abc"), thencheck("10").
Put it together: stock delivery
Deliveries of apples arrive as text, and one of them is garbage. Parse each one, add the good ones to the stock with entry, and report the bad ones instead of crashing.
Loop over
deliveriesandmatchond.parse::<i32>(). ForErr, printBad delivery:and the text.For
Ok(n), addnto the apples with*stock.entry("apples").or_insert(0) += n;. After the loop, printapples: 12.Use
stock.get("bananas")to printNo bananaswhen it'sNone.
More in Rust Data
Previous: Vectors and Strings · Next: Traits and Generics