Rust Fundamentals · 15 XP Pro

Hash maps

A HashMap<K, V> stores key-value pairs and finds a value by its key quickly. It lives in the standard library, so import it first.

use std::collections::HashMap;

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

let n = stock.get("apple");   // Some(&3)
let none = stock.get("plum"); // None

get returns Option<&V>, since the key may be missing. Inserting an existing key replaces its value.

The entry API handles "insert if absent, then update" in one go:

*stock.entry(String::from("apple")).or_insert(0) += 1;

entry(key) looks the key up, or_insert(0) adds it with 0 if it is missing and returns a mutable reference to the value, and * ... += 1 updates it through that reference. This is the classic way to count things.

A hash map has no defined order. Do not rely on the order in which you get items back.

Your task

The tests use these, so they must be pub, and you need use std::collections::HashMap; at the top of your file.

  1. pub fn word_count(text: &str) -> HashMap<String, usize>: split text on whitespace, lowercase each word, and count how often each appears. Use the entry API. Empty text gives an empty map.
  2. pub fn total_for(counts: &HashMap<String, usize>, words: &[&str]) -> usize: add up the counts of the given words. A word not in the map counts as 0.

Next lesson →

Sign in to run your code. It's free.