Skip to content

HashMap

HashMap<K, V> maps keys of type K to values of type V. It uses a hash function internally to achieve O(1) average-case insertion and lookup.

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

Keys must implement Eq and Hash. Common key types — String, &str, integers — already do.

scores.insert(String::from("Alice"), 100);
scores.insert(String::from("Bob"), 85);
// get returns Option<&V>
if let Some(score) = scores.get("Alice") {
println!("Alice: {}", score);
}
// index syntax — panics if key is missing
let bob_score = scores["Bob"];

Prefer .get(key) in production code so you handle the missing-key case gracefully.

The entry API provides a clean way to insert a value only if the key is absent, avoiding a double-lookup:

// Insert 70 for "Dave" if "Dave" is not yet present
scores.entry(String::from("Dave")).or_insert(70);
// Increment a counter — insert 0 first if absent, then add 1
let count = scores.entry(String::from("Eve")).or_insert(0);
*count += 1;

or_insert returns a &mut V pointing at the value, so you can update it in place.

Iterating — Always Sort Keys for Deterministic Output

Section titled “Iterating — Always Sort Keys for Deterministic Output”

HashMap does not guarantee any iteration order. Two runs of the same program can yield different orderings. When output order matters (tests, learning playgrounds, logging), sort the keys first:

let mut keys: Vec<&String> = scores.keys().collect();
keys.sort();
for k in keys {
println!("{}: {}", k, scores[k]);
}
scores.remove("Bob");
println!("Bob present: {}", scores.contains_key("Bob"));
use std::collections::HashMap;
fn main() {
let mut scores: HashMap<String, u32> = HashMap::new();
scores.insert(String::from("Alice"), 100);
scores.insert(String::from("Bob"), 85);
scores.insert(String::from("Carol"), 92);
// entry API: insert if absent
scores.entry(String::from("Dave")).or_insert(70);
// Alice already exists — or_insert does nothing
scores.entry(String::from("Alice")).or_insert(0);
// get returns Option<&V>
if let Some(score) = scores.get("Alice") {
println!("Alice scored {}", score);
}
// deterministic iteration: sort keys
let mut keys: Vec<&String> = scores.keys().collect();
keys.sort();
for k in keys {
println!("{}: {}", k, scores[k]);
}
// remove
scores.remove("Bob");
println!("Bob present: {}", scores.contains_key("Bob"));
}
What does scores.get("Alice") return when Alice is not in the map?
What does entry(key).or_insert(v) do when the key already exists?
Why is HashMap iteration order non-deterministic in Rust?
Which trait bounds must a type satisfy to be used as a HashMap key?