Start learning free

LESSON 136 OF 293 · DICTIONARIES - CHALLENGES

Restock in Rust: Updating a HashMap Value

Practice Read the full explanation

A shop keeps its stock in inventory, a HashMap from item names to how many of each item it has. A delivery brings amount more of item. Add amount to the count of item and return the updated dictionary.

Only the count of item changes: every other entry stays as it is. The order of the entries doesn't matter.

 

Example 1:

Input: inventory = {"apples": 5, "bananas": 2, "cherries": 10}, item = "bananas", amount = 3
Output: {"apples": 5, "bananas": 5, "cherries": 10}
Explanation: "bananas" had a count of 2, and 2 + 3 = 5. The apples and the cherries keep their counts.

Example 2:

Input: inventory = {"milk": 0}, item = "milk", amount = 12
Output: {"milk": 12}
Explanation: A count of 0 means the milk was sold out. The delivery brings it to 0 + 12 = 12.

Example 3:

Input: inventory = {"pens": 7, "paper": 3}, item = "pens", amount = 1
Output: {"pens": 8, "paper": 3}
Explanation: One more pen: 7 + 1 = 8.

 

Constraints:

  • item is always a key of inventory.
  • amount is at least 1.
  • Every count is 0 or more.
  • Item names are single lowercase words, and they are all different.
STEP 1 OF 3
    Ctrl + Enter to check

    RUST · DICTIONARIES - CHALLENGES

    Restock in Rust, explained

    Problem overview

    The function restock receives inventory, a HashMap<String, i32> from item names to counts, an item that is always one of its keys, and an amount to add. It returns the map with the count of item increased by amount. Every other entry stays the same, and the order of entries doesn't matter.

    For {"apples": 5, "bananas": 2, "cherries": 10}, item = "bananas" and amount = 3, the result is {"apples": 5, "bananas": 5, "cherries": 10}.

    Approach

    The update has two parts: read the old count, then store the new one. A HashMap keeps one value per key, and insert on a key that is already there replaces its value. So reading the count and inserting count + amount under the same key is the whole job.

    The function owns the map, because it received it by value. Marking the parameter mut lets the function change that map and then hand it back.

    Step by step

    1. Read the old count. Index the map with &item and store the number in count. Indexing only borrows the key, so item is still available for the next step.
    2. Insert the new count. Call insert with item and count + amount. The key already exists, so its value is replaced.
    3. Return the map. It was changed in place, so it holds every entry, with only one count different.

    The solution in Rust

    impl Solution {
        fn restock(mut inventory: HashMap<String, i32>, item: String, amount: i32) -> HashMap<String, i32> {
            let count = inventory[&item];
            inventory.insert(item, count + amount);
            return inventory;
        }
    }
    
    • Why count is a separate variable. inventory[&item] borrows the map. Reading it into count first ends that borrow, because an i32 is copied out. Only then can insert borrow the map mutably. Splitting the read from the write keeps each line doing one thing, and the borrow checker has nothing to question.
    • Moving item. insert(item, ...) takes ownership of the key, so item can't be used after that line. That is why the read, which borrows, comes first.
    • insert returns an Option. It gives back the previous value, Some(7) when replacing a 7 and None for a new key. The code ignores it.
    • Return type. The function returns the same HashMap<String, i32> it received, now updated.

    Following one update

    Take {"pens": 7}, item = "pens" and amount = 1. Reading gives count = 7. Inserting "pens" with 8 replaces the 7, and the call returns Some(7), the value that was replaced. Inserting a key that wasn't there, such as "ink", returns None. In both cases the map ends up with exactly one value per key, so the map never holds two "pens" entries.

    Edge cases and common mistakes

    • A count of 0. {"milk": 0} with amount = 12 gives {"milk": 12}. A zero count is a normal value, and the key is still present.
    • Inserting only the amount. inventory.insert(item, amount) would overwrite the old count instead of adding to it.
    • Other entries. They are untouched. insert changes only the value under the key you give it.
    • An absent item. Indexing a missing key panics. The lesson guarantees the item is present. For code that must also handle a new item, *inventory.entry(item).or_insert(0) += amount; adds to the count and creates the entry with 0 when it is missing.

    Testing

    • {"apples": 5, "bananas": 2, "cherries": 10}, "bananas", 3 gives apples 5, bananas 5, cherries 10.
    • {"milk": 0}, "milk", 12 gives {"milk": 12}.
    • {"pens": 7, "paper": 3}, "pens", 1 gives paper 3, pens 8.
    Keep going with Rust1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free