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
- Read the old count. Index the map with
&itemand store the number incount. Indexing only borrows the key, soitemis still available for the next step. - Insert the new count. Call
insertwithitemandcount + amount. The key already exists, so its value is replaced. - 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
countis a separate variable.inventory[&item]borrows the map. Reading it intocountfirst ends that borrow, because ani32is copied out. Only then caninsertborrow 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, soitemcan't be used after that line. That is why the read, which borrows, comes first. insertreturns anOption. It gives back the previous value,Some(7)when replacing a 7 andNonefor 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}withamount = 12gives{"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.
insertchanges 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.
