Start learning free

LESSON 107 OF 348 · DICTIONARIES

Updating Dictionary Values in Rust in Rust

Lesson

In Rust, you update a value in a HashMap by calling insert() with an existing key:

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

scores.insert("Alice", 99);     // update: Alice is now 99
scores.insert("Charlie", 72);   // add new entry

The insert() method both creates new entries and updates existing ones. You can also use the entry API to update only existing keys:

scores.entry("Alice").and_modify(|v| *v = 99);  // updates Alice if exists

Assignment
Follow the Coding Tutorial and update Alice's score to 99!


Hint
Use scores.insert("Alice", 99).

STEP 1 OF 1
    Ctrl + Enter to check

    Updating 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