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 price 3 and "bread" with price 2.

  • Print 2 items using prices.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 let with prices.get("apple") to print apple costs 3.

  • Use match on prices.get("cake"): print the price for Some, and No cake today for None.

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 words and count each one with entry and or_insert(0).

  • Print cat: 3 and then dog: 1, reading the numbers from counts.

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 parses text as an i32. On Ok(n) print Double: and n * 2. On Err print Not a number.

  • Call check("123"), then check("abc"), then check("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 deliveries and match on d.parse::<i32>(). For Err, print Bad delivery: and the text.

  • For Ok(n), add n to the apples with *stock.entry("apples").or_insert(0) += n;. After the loop, print apples: 12.

  • Use stock.get("bananas") to print No bananas when it's None.

More in Rust Data

Previous: Vectors and Strings · Next: Traits and Generics