HashMap
HashMap<K, V>
Section titled “HashMap<K, V>”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.
Inserting and Reading Values
Section titled “Inserting and Reading Values”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 missinglet bob_score = scores["Bob"];Prefer .get(key) in production code so you handle the missing-key case gracefully.
The Entry API
Section titled “The Entry API”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 presentscores.entry(String::from("Dave")).or_insert(70);
// Increment a counter — insert 0 first if absent, then add 1let 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]);}Removing Entries
Section titled “Removing Entries”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"));}Compiling…