HashMaps
Key-value storage.
HashMaps is a free Learn Rust Coding lesson on CoddyKit — lesson 3 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Learn Rust Coding learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.
What Is a HashMap?
A HashMap<K, V> stores key-value pairs. You look up values by their key instead of by position.
You must import it from the standard library.
use std::collections::HashMap;
fn main() {
let map: HashMap<String, i32> = HashMap::new();
println!("{} entries", map.len());
}Importing HashMap
HashMap is not in the prelude, so add this line at the top of your file:
use std::collections::HashMap;
use std::collections::HashMap;
fn main() {
let scores: HashMap<&str, i32> = HashMap::new();
println!("empty: {}", scores.is_empty());
}Inserting Pairs
Add entries with insert, giving a key and a value. The map must be mut.
use std::collections::HashMap;
fn main() {
let mut scores = HashMap::new();
scores.insert("Alice", 90);
scores.insert("Bob", 85);
println!("{:?}", scores);
}Looking Up Values
Use get to read a value by key. It returns an Option — Some(value) if found, None otherwise.
use std::collections::HashMap;
fn main() {
let mut scores = HashMap::new();
scores.insert("Alice", 90);
match scores.get("Alice") {
Some(s) => println!("score {}", s),
None => println!("not found"),
}
}Updating a Value
Calling insert with an existing key replaces the old value.
use std::collections::HashMap;
fn main() {
let mut map = HashMap::new();
map.insert("count", 1);
map.insert("count", 5); // overwrites
println!("{:?}", map.get("count"));
}Insert Only If Absent
The entry API with or_insert inserts a default only if the key is missing.
use std::collections::HashMap;
fn main() {
let mut map = HashMap::new();
map.entry("x").or_insert(10);
map.entry("x").or_insert(99); // ignored, key exists
println!("{:?}", map.get("x"));
}Counting with entry
A classic pattern: count occurrences by getting a mutable reference with or_insert and incrementing it.
use std::collections::HashMap;
fn main() {
let text = "a b a c b a";
let mut counts = HashMap::new();
for word in text.split_whitespace() {
let c = counts.entry(word).or_insert(0);
*c += 1;
}
println!("{:?}", counts);
}Iterating Entries
Loop over a HashMap to visit every key-value pair. The order is not guaranteed.
use std::collections::HashMap;
fn main() {
let mut ages = HashMap::new();
ages.insert("Tom", 30);
ages.insert("Sue", 25);
for (name, age) in &ages {
println!("{} is {}", name, age);
}
}Removing Entries
Delete a pair with remove. It returns the removed value as an Option.
use std::collections::HashMap;
fn main() {
let mut map = HashMap::new();
map.insert("key", 42);
let removed = map.remove("key");
println!("removed {:?}, len {}", removed, map.len());
}Checking for a Key
Use contains_key to test whether a key exists without retrieving its value.
use std::collections::HashMap;
fn main() {
let mut map = HashMap::new();
map.insert("on", true);
println!("{}", map.contains_key("on"));
println!("{}", map.contains_key("off"));
}Default with unwrap_or
When reading, you can supply a fallback with unwrap_or instead of matching the Option.
use std::collections::HashMap;
fn main() {
let mut map = HashMap::new();
map.insert("a", 1);
let value = map.get("missing").unwrap_or(&0);
println!("{}", value);
}Quick Check
Recall how HashMap lookups behave.
Recap
HashMaps in Rust:
HashMap<K, V>stores key-value pairs; import fromstd::collections.insertadds or overwrites;getreturns an Option.entry().or_insert()inserts only if absent.- Iterate with
for (k, v) in &map.
use std::collections::HashMap;
fn main() {
let mut inventory = HashMap::new();
inventory.insert("apples", 3);
*inventory.entry("apples").or_insert(0) += 2;
println!("{:?}", inventory.get("apples"));
}Frequently asked questions
Is the “HashMaps” lesson free?
Yes — the full text of “HashMaps” is free to read here on the web, and the Learn Rust Coding course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Learn Rust Coding course, upgrade to CoddyKit PRO.
What will I learn in “HashMaps”?
Key-value storage. You practise Learn Rust Coding with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.
Do I need any experience to start Learn Rust Coding?
No prior experience is required. Learn Rust Coding on CoddyKit is structured for beginners through advanced learners; this is — lesson 3 of 4, so you can start here or from the beginning and move at your own pace.
How long does the “HashMaps” lesson take?
Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.
Can I write and run code in this Learn Rust Coding lesson?
Yes. Every Learn Rust Coding lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.