HashMap Basics
HashMap lets you store values under labels you choose, like a labeled filing cabinet you can search by name instantly.In this page:
Creating and Inserting
A HashMap is created with HashMap::new() and populated using .insert(key, value), which stores or overwrites the value for that key.
Example: Creating and Inserting
use std::collections::HashMap;
fn main() {
let mut scores = HashMap::new();
scores.insert("Alice", 90);
scores.insert("Bob", 85);
println!("{:?}", scores.get("Alice"));
}
Login to try C/C++/Java/PHP code in the editor
Retrieving Values Safely
.get(&key) returns an Option<&V>, letting you safely handle the case where a key is not present in the map.
Example: Retrieving Values Safely
use std::collections::HashMap;
fn main() {
let mut ages = HashMap::new();
ages.insert("Sam", 25);
match ages.get("Sam") {
Some(age) => println!("Sam is {}", age),
None => println!("Sam not found"),
}
}
Login to try C/C++/Java/PHP code in the editor
Overwriting an Existing Key
Inserting a value for a key that already exists silently replaces the old value -- there is no error or warning by default.
Example: Overwriting an Existing Key
use std::collections::HashMap;
fn main() {
let mut inventory = HashMap::new();
inventory.insert("apples", 10);
inventory.insert("apples", 15);
println!("{:?}", inventory.get("apples"));
}
Login to try C/C++/Java/PHP code in the editor
Iterating a HashMap
A for loop over &map yields (&key, &value) pairs, though the order of iteration is not guaranteed to match insertion order.
Example: Iterating a HashMap
use std::collections::HashMap;
fn main() {
let mut colors = HashMap::new();
colors.insert("red", "#FF0000");
colors.insert("blue", "#0000FF");
let mut keys: Vec<&&str> = colors.keys().collect();
keys.sort();
for k in keys {
println!("{}: {}", k, colors[k]);
}
}
Login to try C/C++/Java/PHP code in the editor
- Forgetting to
use std::collections::HashMap;before trying to use it. - Assuming
HashMappreserves insertion order like some other languages' dictionaries -- Rust'sHashMaphas no guaranteed order. - Calling
.insert()with a key that already exists and being surprised the old value is silently overwritten.
HashMap<K, V>stores key-value pairs and requiresuse std::collections::HashMap;..insert(key, value)adds or overwrites an entry;.get(&key)retrieves it as anOption.- Iteration order over a
HashMapis not guaranteed and can vary between runs. - Keys must implement the
EqandHashtraits, which most built-in types already do.
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: