Rust — HashMap
The key → value collection
use std::collections::HashMap;
let mut scores: HashMap<String, i32> = HashMap::new();
scores.insert(String::from("Ada"), 95);
scores.insert(String::from("Bo"), 87);
scores.get("Ada"); // Some(&95)
scores.len(); // 2
Unlike vectors, keys have no order — lookup is by hash, near-instant regardless of size.
Reading values — always through Option
scores.get("Bo"); // Some(&87)
scores.get("Zoe"); // None — no panic, ever
// dereference the & to get the number:
if let Some(score) = scores.get("Ada") {
println!("{}", score);
}
// or provide a default:
let zoes = scores.get("Zoe").copied().unwrap_or(0);
Insert overwrites; entry() inserts only-if-missing
scores.insert("Ada", 100); // replaces 95 silently
// entry(): get-or-create pattern:
scores.entry("New".to_string()).or_insert(0);
The frequency-counting idiom
The most famous HashMap pattern:
let text = "the quick the lazy the";
let mut counts: HashMap<&str, i32> = HashMap::new();
for word in text.split_whitespace() {
*counts.entry(word).or_insert(0) += 1;
}
// {"the": 3, "quick": 1, "lazy": 1}
entry(word).or_insert(0) returns a mutable reference to the existing-or-new value; *… += 1 increments it. Memorize this shape.
Updating based on old value
if let Some(score) = scores.get_mut("Ada") {
*score += 5; // bonus points — needs get_mut + *
}
Iteration
for (name, score) in &scores {
println!("{}: {}", name, score);
}
Order is random by design (hash-based) — never rely on it. Sort into a vector if order matters:
let mut pairs: Vec<_> = scores.iter().collect();
pairs.sort_by(|a, b| b.1.cmp(a.1)); // highest score first
Ownership rules for keys and values
Insert MOVES non-Copy data into the map:
let key = String::from("config");
map.insert(key, 1);
println!("{}", key); // ❌ moved into the map!
Borrowing keys keeps originals:
map.insert(&key_name, value); // map borrows; caller keeps owner
HashMap vs Vectors
| Need | Collection |
|---|---|
| Ordered list, positions matter | Vec<T> |
| Lookup by identifier | HashMap<K, V> |
| "Have I seen this?" | HashSet<T> (next-adjacent) |
Gotchas: forgetting
use std::collections::HashMap·get()returnsOption<&V>notV· insertion order is NOT iteration order · integer/float keys work but String/&str are the daily bread.
Mini Practice
- Phone-book: insert three contacts; look up one; handle a miss.
- Word-frequency counter on any sentence.
- Increment every score by 10 via get_mut.
- Print top-3 scorers via collect + sort_by.
- Prove iteration order randomness across runs.
Next: structs →
Related Topics
Frequently Asked Questions about HashMap
What is HashMap in Rust?
HashMap is a fundamental concept in Rust. This lesson explains it step by step with clear examples, making it easy for beginners to understand.
How do I learn HashMap?
Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn HashMap.
Why is HashMap important in Rust?
HashMap is essential for Rust development. Understanding this concept will help you write better code and solve real-world problems more effectively.