Rust HashMap
HashMap
A HashMap is a collection of key/value pairs.
HashMaps are great when you want to store values and find them by a key.
To use HashMap, you must import it from Rust's standard library:
use std::collections::HashMap;
Create a HashMap
You can create a new, empty HashMap and add items to it:
Example
// Import HashMap
use std::collections::HashMap;
fn main() {
// Create a
HashMap called capital_cities
let mut capital_cities = HashMap::new();
// Add keys and values (Country, City)
capital_cities.insert("England", "London");
capital_cities.insert("Germany", "Berlin");
capital_cities.insert("Norway", "Oslo");
println!("{:?}",
capital_cities);
}
Try it Yourself »
Note: A HashMap does not keep its items in a fixed order. When you print it, the order can be different each time you run the program.
Access Values
You can use the .get() method to access a value in a HashMap by its key:
Example
let mut capital_cities = HashMap::new();
capital_cities.insert("England",
"London");
capital_cities.insert("Germany", "Berlin");
capital_cities.insert("Norway", "Oslo");
if let Some(city) =
capital_cities.get("England") {
println!("The capital of
England is {}.", city);
} else {
println!("England is not in the
map.");
}
Try it Yourself »
.get() does not know if the key exists, so it gives back Some(value) when the key is found, and None when it is not. if let Some(city) runs the first block only when a value was found, and stores it in city. You will learn more about Some and None in the Rust Option chapter.
Update Values
If you insert a new value using a key that already exists, the old value is replaced with the new one:
Example
let mut
capital_cities = HashMap::new();
capital_cities.insert("England",
"London");
capital_cities.insert("England", "Berlin");
println!("{:?}", capital_cities);
Try it Yourself »
Remove Values
To remove a key from a HashMap, use the .remove() method:
Example
let mut capital_cities = HashMap::new();
// Add keys and values
(Country, City)
capital_cities.insert("England", "London");
capital_cities.insert("Germany",
"Berlin");
capital_cities.insert("Norway", "Oslo");
// Remove the key "England"
capital_cities.remove("England");
println!("{:?}", capital_cities);
Try it Yourself »
Loop Through a HashMap
You can use a for loop to go through all key/value pairs:
Example
let mut capital_cities = HashMap::new();
// Add keys and values
(Country, City)
capital_cities.insert("England", "London");
capital_cities.insert("Germany", "Berlin");
capital_cities.insert("Norway",
"Oslo");
// Loop through the HashMap
for (country, city) in
&capital_cities {
println!("The capital of {} is {}.", country,
city);
}
Try it Yourself »
Why Use HashMaps?
- To store data by key
- To quickly look up values
- To group related data (like names and scores)
Note: HashMaps require keys to be unique. Inserting the same key again will overwrite the old value.