0PricingLogin
Learn Rust Coding · Lesson

Building a HashMap

Insert and look up by key.

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());
}

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