Exerpad
🔥1
10 XP
Lv.1 Beginner
Log In

Using HashMaps

Imagine you have a notebook where you write down your friends' names and their favorite colors. You look up a name, and you find their color right next to it. That's exactly what a HashMap does in Rust! It stores keys (like names) paired with values (like colors).

Importing HashMap

Unlike vectors, HashMaps aren't included automatically. You need to tell Rust you want to use them:

rust
use std::collections::HashMap;

fn main() {
let mut colors = HashMap::new();
colors.insert("Alice", "blue");
colors.insert("Bob", "green");
colors.insert("Carol", "red");
println!("{:?}", colors);
}

The use std::collections::HashMap; line goes at the very top of your file. After that, you can create HashMaps with HashMap::new() and add entries with .insert(key, value).

Looking Up Values with .get()

To find a value by its key, use .get(). It returns an Option because the key might not exist:

rust
use std::collections::HashMap;

fn main() {
let mut scores = HashMap::new();
scores.insert("Alice", 95);
scores.insert("Bob", 87);

if let Some(score) = scores.get("Alice") {
println!("Alice scored {}", score);
}

if let Some(score) = scores.get("Charlie") {
println!("Charlie scored {}", score);
} else {
println!("Charlie not found!");
}
}

The .get() method returns Some(value) if the key exists, or None if it doesn't. Using if let Some(...) is a safe way to handle both cases.

Checking if a Key Exists

Want to know if a key is in the HashMap without getting its value? Use .contains_key():

rust
use std::collections::HashMap;

fn main() {
let mut pets = HashMap::new();
pets.insert("dog", "Buddy");
pets.insert("cat", "Whiskers");

if pets.contains_key("dog") {
println!("We have a dog!");
}

if !pets.contains_key("fish") {
println!("No fish here.");
}
}

Removing Items and Checking Length

Use .remove() to delete a key-value pair, and .len() to see how many entries are in the map:

rust
use std::collections::HashMap;

fn main() {
let mut snacks = HashMap::new();
snacks.insert("chips", 2);
snacks.insert("cookies", 5);
snacks.insert("fruit", 3);
println!("Snacks: {}", snacks.len());

snacks.remove("chips");
println!("After removing chips: {}", snacks.len());
}

Iterating Over a HashMap

You can loop through all the key-value pairs using a for loop. Use & to borrow the map so you can still use it afterward:

rust
use std::collections::HashMap;

fn main() {
let mut ages = HashMap::new();
ages.insert("Alice", 10);
ages.insert("Bob", 12);
ages.insert("Carol", 11);

for (name, age) in &ages {
println!("{} is {} years old", name, age);
}
}

Important: HashMaps don't store items in any particular order! If you need items in a specific order, you can collect the keys into a vector and sort it first.

Updating Values

If you .insert() a key that already exists, the old value gets replaced:

rust
use std::collections::HashMap;

fn main() {
let mut stock = HashMap::new();
stock.insert("apples", 5);
println!("Apples: {}", stock["apples"]);

stock.insert("apples", 10);
println!("Apples now: {}", stock["apples"]);
}

You can also use the entry() API to only insert if the key doesn't exist yet, or to modify the existing value:

rust
use std::collections::HashMap;

fn main() {
let mut word_count = HashMap::new();
let words = vec!["hello", "world", "hello", "rust"];

for word in &words {
let count = word_count.entry(word).or_insert(0);
*count += 1;
}

let mut keys: Vec<&&str> = word_count.keys().collect();
keys.sort();
for key in keys {
println!("{}: {}", key, word_count[key]);
}
}

The entry().or_insert(0) pattern is super handy for counting things. It gives you a reference to the value, which you can then update with *count += 1.

Summary

ConceptWhat it does
use std::collections::HashMapImports HashMap
HashMap::new()Creates an empty HashMap
.insert(key, value)Adds or updates an entry
.get(key)Returns Some(value) or None
.contains_key(key)Checks if a key exists
.remove(key)Removes an entry
.len()Returns how many entries are in the map
for (k, v) in &mapLoops through all entries
.entry(key).or_insert(val)Insert only if key is missing

Now let's practice using HashMaps!