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:
let mut name: HashMap<K, V> = HashMap::new();
name.insert(key, value);
name.get(&key)
name.remove(&key);
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
// Bring `std::collections::HashMap` into scope
use std::collections::HashMap;
// Entry point: execution of the program starts here
fn main() {
// Declare a mutable variable `scores`, initialized to `HashMap::new()`
let mut scores = HashMap::new();
scores.insert("Alice", 90);
scores.insert("Bob", 85);
// Print "{:?}" to the console, substituting in `scores.get("Alice")` (with a trailing newline)
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
// Bring `std::collections::HashMap` into scope
use std::collections::HashMap;
// Entry point: execution of the program starts here
fn main() {
// Declare a mutable variable `ages`, initialized to `HashMap::new()`
let mut ages = HashMap::new();
ages.insert("Sam", 25);
// Match on `ages.get("Sam")` and branch by pattern
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
// Bring `std::collections::HashMap` into scope
use std::collections::HashMap;
// Entry point: execution of the program starts here
fn main() {
// Declare a mutable variable `inventory`, initialized to `HashMap::new()`
let mut inventory = HashMap::new();
inventory.insert("apples", 10);
inventory.insert("apples", 15);
// Print "{:?}" to the console, substituting in `inventory.get("apples")` (with a trailing newline)
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
// Bring `std::collections::HashMap` into scope
use std::collections::HashMap;
// Entry point: execution of the program starts here
fn main() {
// Declare a mutable variable `colors`, initialized to `HashMap::new()`
let mut colors = HashMap::new();
colors.insert("red", "#FF0000");
colors.insert("blue", "#0000FF");
// Declare a mutable variable `keys` (a `Vec<&&str>`), initialized to `colors.keys().collect()`
let mut keys: Vec<&&str> = colors.keys().collect();
keys.sort();
// Loop over `keys`, binding each item to `k`
for k in keys {
// Print "{}: {}" to the console, substituting in `k, colors[k]` (with a trailing newline)
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: