Rust HashMaps

A HashMap stores data in key-value pairs. You look up a value by providing its key, just like looking up a word in a dictionary to find its definition. HashMaps are ideal when you need fast lookups by name or ID rather than by position.

Creating a HashMap

use std::collections::HashMap;

fn main() {
    let mut scores: HashMap<String, i32> = HashMap::new();
    scores.insert(String::from("Alice"), 95);
    scores.insert(String::from("Bob"), 82);
    scores.insert(String::from("Carol"), 78);

    println!("{:?}", scores);
}

You must import HashMap with use std::collections::HashMap because it is not imported by default like Vec.

The Dictionary Diagram

HashMap:
  "Alice" → 95
  "Bob"   → 82
  "Carol" → 78

You give a key, you get a value.

Accessing Values

let score = scores.get("Alice");

match score {
    Some(s) => println!("Alice scored {}.", s),
    None    => println!("Alice not found."),
}

get() returns Option<&V> — a reference to the value, wrapped in Option. It returns None if the key does not exist.

Iterating Over a HashMap

for (name, score) in &scores {
    println!("{}: {}", name, score);
}

The order of iteration is not guaranteed. HashMaps do not store items in insertion order.

Updating Values

Overwrite Existing

scores.insert(String::from("Alice"), 100);   ← Old value 95 is replaced

Only Insert If Key Does Not Exist

scores.entry(String::from("Dave")).or_insert(70);

entry checks if the key exists. or_insert inserts the default value only if the key is absent. This is a very common pattern for initializing counters and accumulators.

Modify an Existing Value

let count = word_count.entry(String::from("hello")).or_insert(0);
*count += 1;   ← Dereference to modify the value directly

Checking for Keys

if scores.contains_key("Alice") {
    println!("Alice is in the map.");
}

Removing Entries

scores.remove("Bob");   ← Bob's entry is deleted

HashMap vs Vector

Feature         Vector          HashMap
-------         ------          -------
Access by       Index (0, 1, 2) Key (any type)
Order           Preserved       Not guaranteed
Use when        List of items   Lookup by name or ID
Speed           O(1) by index   O(1) by key (average)

Quick Reference

HashMap::new()              ← Create empty map
map.insert(k, v)            ← Add or overwrite entry
map.get(&k)                 ← Look up value (returns Option)
map.contains_key(&k)        ← Check if key exists
map.remove(&k)              ← Delete entry
map.entry(k).or_insert(v)   ← Insert only if absent
for (k, v) in &map          ← Iterate all entries

Leave a Comment