← Back to Rust Course | Chapter 9: Collections | Lesson 3 of 6

HashMap Basics

A HashMap lets you store values under labels you choose, like a labeled filing cabinet you can search by name instantly.

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

markup
use std::collections::HashMap;

fn main() {
    let mut scores = HashMap::new();
    scores.insert("Alice", 90);
    scores.insert("Bob", 85);
    println!("{:?}", scores.get("Alice"));
}

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

markup
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"),
    }
}

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

markup
use std::collections::HashMap;

fn main() {
    let mut inventory = HashMap::new();
    inventory.insert("apples", 10);
    inventory.insert("apples", 15);
    println!("{:?}", inventory.get("apples"));
}

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

markup
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]);
    }
}
Common Mistakes
  1. Forgetting to use std::collections::HashMap; before trying to use it.
  2. Assuming HashMap preserves insertion order like some other languages' dictionaries -- Rust's HashMap has no guaranteed order.
  3. Calling .insert() with a key that already exists and being surprised the old value is silently overwritten.
Chapter Summary
  • HashMap<K, V> stores key-value pairs and requires use std::collections::HashMap;.
  • .insert(key, value) adds or overwrites an entry; .get(&key) retrieves it as an Option.
  • Iteration order over a HashMap is not guaranteed and can vary between runs.
  • Keys must implement the Eq and Hash traits, which most built-in types already do.
🔒

Chapter Quiz — Complete all 6 topics to unlock

0/6 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.