Rust HashMaps
A HashMap stores data as key-value pairs — you look things up by a key instead of by position, the way you would with an array or vector. If you’ve used a dictionary in Python or an object-as-map in JavaScript, this is the same idea.
Creating a HashMap
Section titled “Creating a HashMap”use std::collections::HashMap;
fn main() { let mut ages = HashMap::new();
ages.insert("Alice", 30); ages.insert("Bob", 25);
println!("{:?}", ages);}use std::collections::HashMap; at the top brings the type into scope — unlike Vec and String, HashMap isn’t available by default, so this line is required.
Looking up a value
Section titled “Looking up a value”use std::collections::HashMap;
fn main() { let mut ages = HashMap::new(); ages.insert("Alice", 30);
match ages.get("Alice") { Some(age) => println!("Alice is {age}"), None => println!("Not found"), }}.get() returns an Option rather than the value directly, because the key might not exist. We’ll cover Option properly on its own page — for now, match with Some/None is the standard way to handle it.
Updating a value
Section titled “Updating a value”Inserting again with the same key overwrites the old value:
use std::collections::HashMap;
fn main() { let mut ages = HashMap::new(); ages.insert("Alice", 30); ages.insert("Alice", 31); // overwrites 30
println!("{:?}", ages.get("Alice"));}If you only want to insert a value when the key doesn’t already exist, use .entry():
use std::collections::HashMap;
fn main() { let mut ages = HashMap::new(); ages.insert("Alice", 30);
ages.entry("Alice").or_insert(99); // Alice exists, so this does nothing ages.entry("Bob").or_insert(25); // Bob doesn't exist, so this inserts it
println!("{:?}", ages);}Looping over a HashMap
Section titled “Looping over a HashMap”use std::collections::HashMap;
fn main() { let mut ages = HashMap::new(); ages.insert("Alice", 30); ages.insert("Bob", 25);
for (name, age) in &ages { println!("{name} is {age}"); }}When to use a HashMap
Section titled “When to use a HashMap”Reach for a HashMap whenever you want to look things up by a name or ID instead of a position — counting word frequency, mapping usernames to user data, caching results by key. If order matters or you’re just working through a plain list, a Vec is the better fit.
HashMap<K, V>stores key-value pairs; bring it into scope withuse std::collections::HashMap;..insert(key, value)adds or overwrites;.get(key)looks up and returns anOption..entry(key).or_insert(value)inserts only if the key isn’t already there.- Iteration order isn’t guaranteed — don’t rely on it.