← 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.
Syntax
rust
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

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

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

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
// 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"));
}

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
// 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]);
    }
}
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
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.