0Pricing
Learn Rust Coding · Lesson

Building a HashMap

Insert and look up by key.

Building a HashMap is a free Learn Rust Coding lesson on CoddyKit. This is lesson 1 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, and your progress syncs across the web and the CoddyKit app. The Learn Rust Coding course includes 4 lessons in total.

What Is a HashMap?

A HashMap stores data as key-value pairs. You look things up by key instead of by index.

Think of a phone book: a name (key) maps to a number (value). HashMaps are perfect when you need fast lookups by a meaningful key.

Importing HashMap

Unlike Vec and String, HashMap is not in the prelude. You must bring it into scope.

Add a use line at the top of your file. This makes the name available throughout the module.

use std::collections::HashMap;

fn main() {
    let scores: HashMap<String, i32> = HashMap::new();
    println!("empty map len: {}", scores.len());
}

Inserting Pairs

Use insert to add a key and its value. If the key already exists, the old value is replaced.

The map must be declared mut to allow insertion.

use std::collections::HashMap;

fn main() {
    let mut scores = HashMap::new();
    scores.insert("Alice", 50);
    scores.insert("Bob", 30);
    println!("{} players", scores.len());
}

Type Inference

You rarely need to write the type. Rust infers HashMap<&str, i32> from the first insert calls.

Here the keys are string slices and the values are integers, all decided by usage.

use std::collections::HashMap;

fn main() {
    let mut ages = HashMap::new();
    ages.insert("Sam", 28);
    ages.insert("Mia", 34);
    println!("Sam is {}", ages["Sam"]);
}

Getting Values

The get method returns an Option. You get Some(&value) if the key exists, or None if it does not.

This forces you to handle the missing case safely.

use std::collections::HashMap;

fn main() {
    let mut scores = HashMap::new();
    scores.insert("Alice", 50);
    match scores.get("Alice") {
        Some(v) => println!("score: {}", v),
        None => println!("no score"),
    }
}

Indexing vs get

You can index with map[key], but it panics if the key is missing.

Prefer get when a key might not exist. Use indexing only when you are certain the key is present.

use std::collections::HashMap;

fn main() {
    let mut m = HashMap::new();
    m.insert("x", 1);
    // m["y"] would panic!
    let v = m.get("y").copied().unwrap_or(0);
    println!("y = {}", v);
}

Updating a Value

Calling insert with an existing key overwrites the old value.

The previous value is returned (wrapped in Option) so you can inspect it if you like.

use std::collections::HashMap;

fn main() {
    let mut m = HashMap::new();
    m.insert("k", 1);
    let old = m.insert("k", 9);
    println!("old = {:?}, now = {}", old, m["k"]);
}

Checking Keys

Use contains_key to test whether a key exists without retrieving its value.

It returns a plain bool, which is handy in if conditions.

use std::collections::HashMap;

fn main() {
    let mut m = HashMap::new();
    m.insert("on", true);
    if m.contains_key("on") {
        println!("key exists");
    }
}

Removing Entries

The remove method deletes a key and returns its value as an Option.

If the key was not present you get None, so removal is always safe.

use std::collections::HashMap;

fn main() {
    let mut m = HashMap::new();
    m.insert("a", 1);
    let removed = m.remove("a");
    println!("removed {:?}, len {}", removed, m.len());
}

Iterating Over a Map

A for loop over a HashMap yields (key, value) tuples by reference.

Note the order is unspecified and may change between runs, since hashing scrambles placement.

use std::collections::HashMap;

fn main() {
    let mut m = HashMap::new();
    m.insert("a", 1);
    m.insert("b", 2);
    for (k, v) in &m {
        println!("{} -> {}", k, v);
    }
}

Ownership of Keys

When you insert owned values like a String, the map takes ownership.

After insertion you cannot use that variable again unless you cloned it first.

use std::collections::HashMap;

fn main() {
    let mut m = HashMap::new();
    let name = String::from("Alice");
    m.insert(name, 50);
    // name is moved here; m owns it now
    println!("{}", m["Alice"]);
}

Quick Check

You want a value but the key might be missing.

Recap

You learned to create a HashMap, insert pairs, and look up values with get or indexing.

You also saw contains_key, remove, iteration, and how the map takes ownership of inserted keys.

Frequently Asked Questions

Is the “Building a HashMap” lesson free?

Yes — the full text of “Building a HashMap” is free to read here on the web. 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. The Learn Rust Coding course includes 4 lessons in total.

What will I learn in “Building a HashMap”?

Insert and look up by key. 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, so you can start here or from the beginning and move at your own pace. This is lesson 1 of 4.

How long does the “Building a HashMap” 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.

All lessons in this course

  1. Building a HashMap
  2. Entry API and Defaults
  3. Working with HashSet
  4. Counting and Grouping
← Back to Learn Rust Coding