Start learning free

LESSON 106 OF 348 · DICTIONARIES

Accessing Dictionary Values in Rust in Rust

Lesson

In Rust, you access values in a HashMap using square bracket notation or get():

use std::collections::HashMap;

let mut scores = HashMap::new();
scores.insert("Alice", 95);
scores.insert("Bob", 87);

let alice_score = scores["Alice"];  // 95
let bob_score = scores["Bob"];      // 87

Note: scores["key"] panics if the key doesn't exist. Use get() to get an Option instead, or contains_key() to check existence:

if scores.contains_key("Alice") {
    println!("{}", scores["Alice"]);
}

Assignment
Follow the Coding Tutorial and access Alice's score from scores!


Hint
Use scores["Alice"] and assign it to alice_score.

STEP 1 OF 1
    Ctrl + Enter to check

    Accessing Dictionary Values 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