HashMap<K, V>

A hash map (dictionary) that stores key-value pairs with O(1) average lookup.

Construction

let mut map: HashMap<String, i32> = HashMap::new();

Insertion

map.insert("alice", 42);
map.insert("bob", 17);
map.insert("carol", 99);

Lookup

let value = map.get("alice");    // Option<i32>

match map.get("alice") {
    Option::Some(v) => println!("Found: {}", v),
    Option::None => println!("Not found"),
}

Checking Membership

let exists = map.contains_key("alice");   // bool

Removal

let removed = map.remove("bob");    // Option<i32>

Size

let count = map.len();         // number of entries
let empty = map.is_empty();    // true if len == 0

Iteration

for (key, value) in map {
    println!("{}: {}", key, value);
}

Common Patterns

Word Counter

fn count_words(text: String) -> HashMap<String, i32> {
    let mut counts: HashMap<String, i32> = HashMap::new();
    let words = text.split(" ");
    for word in words {
        let current = counts.get(word).unwrap_or(0);
        counts.insert(word, current + 1);
    }
    counts
}

Configuration Store

pub struct Config {
    values: HashMap<String, String>,
}

impl Config {
    pub fn get(self, key: String) -> Option<String> {
        self.values.get(key)
    }

    pub fn set(mut self, key: String, value: String) {
        self.values.insert(key, value);
    }
}