Start learning free

LESSON 105 OF 348 · DICTIONARIES

Dictionaries (HashMap) in Rust in Rust

Lesson

In Rust, a HashMap works like a dictionary — it stores key-value pairs where each key maps to a value. Bring it into scope with use std::collections::HashMap;.

use std::collections::HashMap;

let mut scores: HashMap<&str, i32> = HashMap::new();
scores.insert("Alice", 95);
scores.insert("Bob", 87);
scores.insert("Charlie", 72);

The type parameters <&str, i32> specify the key type and value type. You can also initialize using HashMap::from:

use std::collections::HashMap;

let ages: HashMap<&str, i32> = HashMap::from([
    ("Alice", 25),
    ("Bob", 30),
]);
println!("{}", ages["Alice"]);  // 25
println!("{}", ages.len());     // 2

Assignment
Follow the Coding Tutorial and create a HashMap named scores with three student scores!


Hint
Declare let mut scores: HashMap<&str, i32> = HashMap::new(); then use scores.insert("Alice", 95) to add entries.

STEP 1 OF 2
    Ctrl + Enter to check

    Dictionaries in Rust

    Keep going with RustAbout 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free