title: HashMap

A HashMap<K, V> stores key-value pairs. Given a key, you can look up its value in constant time. Keys must be unique.

Creating a HashMap

use std::collections::HashMap;
 
let mut scores: HashMap<String, i32> = HashMap::new();

Or build one from an iterator of tuples:

let scores: HashMap<&str, i32> = vec![
    ("Alice", 10),
    ("Bob", 20),
]
.into_iter()
.collect();

Inserting and updating

let mut scores = HashMap::new();
 
scores.insert(String::from("Alice"), 10);
scores.insert(String::from("Bob"), 20);
 
// overwrite an existing value
scores.insert(String::from("Alice"), 99);

Insert only if the key doesn’t exist

scores.entry(String::from("Alice")).or_insert(50);  // does nothing, Alice already exists
scores.entry(String::from("Carol")).or_insert(50);  // inserts Carol with 50

entry is also useful for updating based on the existing value:

let count = scores.entry(String::from("Alice")).or_insert(0);
*count += 1;  // increment, whether Alice existed or not

Reading values

let score = scores.get("Alice");  // returns Option<&i32>
 
match score {
    Some(s) => println!("Alice scored {s}"),
    None => println!("Alice not found"),
}

Or with a default:

let score = scores.get("Alice").copied().unwrap_or(0);

Checking for a key

scores.contains_key("Alice");  // true or false

Removing a key

scores.remove("Alice");  // returns Option<i32> with the removed value

Iterating

for (name, score) in &scores {
    println!("{name}: {score}");
}

Note: HashMap does not guarantee any particular order when iterating.

Ownership

When you insert owned values, the HashMap takes ownership of them:

let key = String::from("Alice");
let value = String::from("hello");
 
scores.insert(key, value);
 
// println!("{key}");  // ERROR — key was moved into the map

If you use references as keys, they must outlive the HashMap.

Common methods

scores.len();        // number of entries
scores.is_empty();   // true if no entries
scores.keys();       // iterator over keys
scores.values();     // iterator over values
scores.clear();      // remove all entries