HasMap
A HashMap stores data as key–value pairs, allowing you to look up values quickly using keys.
Think of it like:
A dictionary: word → meaning A phonebook: name → phone number
use std::collections::HashMap;
let mut scores = HashMap::new();
K→ key typeV→ value type- Stored on the heap
- Keys must be hashable
use std::collections::HashMap;
let mut scores = HashMap::new();
scores.insert("Alice", 90);
scores.insert("Bob", 85);
Maps names to scores.
Key Characteristics of HashMap
| Feature | HashMap |
|---|---|
| Storage | Key–Value pairs |
| Access time | O(1) average |
| Order | ❌ Not guaranteed |
| Duplicate keys | ❌ Not allowed |
| Memory | Heap |
| Mutability | Optional |
Creating HashMaps
Using new():
let mut map: HashMap<String, i32> = HashMap::new();
From Vectors (using collect())
use std::collections::HashMap;
let keys = vec!["a", "b", "c"];
let values = vec![1, 2, 3];
let map: HashMap<_, _> =
keys.into_iter().zip(values).collect();
Inserting and Updating Values
Insert
let mut scores = HashMap::new();
scores.insert("Alice", 90);
Overwriting Existing Value
scores.insert("Alice", 95); // replaces 90
Insert Only If Key Doesn’t Exist (entry)
scores.entry("Bob").or_insert(80);
Very useful pattern.
Accessing Values
Using get()
match scores.get("Alice") {
Some(score) => println!("Score: {}", score),
None => println!("Not found"),
}
Returns Option<&V>
Using Index Syntax (Panics)
let score = scores["Alice"];
Panics if key doesn’t exist.
Iterating Over a HashMap
for (name, score) in &scores {
println!("{}: {}", name, score);
}
Order is random.
HashMaps and Ownership
Ownership Is Transferred on Insert
let name = String::from("Alice");
let mut map = HashMap::new();
map.insert(name, 90);
// name is no longer usable
Using References as Keys
let mut map: HashMap<&str, i32> = HashMap::new();
map.insert("Alice", 90);
String literals live for the entire program.
Updating Values Based on Old Value
Classic Word Count Example
use std::collections::HashMap;
let text = "hello rust hello world";
let mut map = HashMap::new();
for word in text.split_whitespace() {
let count = map.entry(word).or_insert(0);
*count += 1;
}
Result:
hello → 2
rust → 1
world → 1
- Removing Entries:
scores.remove("Bob"); - Checking for Keys
if scores.contains_key("Alice") {
println!("Alice exists");
}
HashMap with Custom Types
Using Structs as Values
struct User {
age: i32,
}
let mut users = HashMap::new();
users.insert("Alice", User { age: 25 });
Keys Must Implement Traits
Keys must implement: Eq, Hash
Most basic types already do.
HashMap vs Vec of Tuples
| Feature | HashMap | Vec<(K, V)> |
|---|---|---|
| Lookup | Fast | Slow |
| Order | Unordered | Ordered |
| Best for | Frequent search | Small datasets |