Start learning free

LESSON 137 OF 293 · DICTIONARIES - CHALLENGES

Safe Lookup in Rust: HashMap get and unwrap_or

Practice Read the full explanation

Given a HashMap scores from names to scores and a name, return the score of name, or 0 when name isn't a key of scores.

Some names you look up aren't in the dictionary at all. They have no score, so the answer for them is 0.

 

Example 1:

Input: scores = {"Ana": 90, "Ben": 75, "Cara": 88}, name = "Ben"
Output: 75
Explanation: "Ben" is a key of scores, and its value is 75.

Example 2:

Input: scores = {"Ana": 90, "Ben": 75, "Cara": 88}, name = "Dan"
Output: 0
Explanation: "Dan" isn't a key of scores, so the answer is 0.

Example 3:

Input: scores = {}, name = "Ana"
Output: 0
Explanation: An empty dictionary has no keys at all.

 

Constraints:

  • scores can be empty.
  • Names are single words made of English letters, and the names in scores are all different.
  • name matches a key only when it is spelled exactly the same, upper and lower case included: "ana" is not "Ana".
  • Every score is between 0 and 100.
STEP 1 OF 1
    Ctrl + Enter to check

    RUST · DICTIONARIES - CHALLENGES

    Safe Lookup in Rust, explained

    Problem overview

    The function safe_lookup receives scores, a HashMap<String, i32> from names to scores, and a name. It returns the score of name, or 0 when the name isn't a key. The map may be empty, and names must match exactly: "ana" is not "Ana".

    With {"Ana": 90, "Ben": 75, "Cara": 88}, the name "Ben" gives 75 and "Dan" gives 0. An empty map gives 0 for any name.

    Approach

    Indexing with scores[&name] would panic for a missing key, so it can't be used here. The safe tool is get. It returns an Option: Some holding a reference to the value when the key exists, and None when it doesn't.

    The task then reduces to "take the value from the Option, or use 0". That is what unwrap_or does.

    Step by step

    1. Call get(&name). The result is an Option<&i32>.
    2. Call unwrap_or(&0). It returns the reference inside Some, or the default you pass when the option is None. The default must be a reference too, so it is &0.
    3. Dereference with *. The expression is now a &i32, and the function returns an i32.

    The solution in Rust

    impl Solution {
        fn safe_lookup(scores: HashMap<String, i32>, name: String) -> i32 {
            return *scores.get(&name).unwrap_or(&0);
        }
    }
    
    • Types along the way. scores.get(&name) is Option<&i32>. unwrap_or(&0) turns it into &i32. The leading * applies to that whole call chain and gives the plain i32. Scores are small, copyable numbers, so copying one out of the reference is cheap.
    • A reference to a literal. &0 may look odd. Rust lets the compiler keep that constant alive for the whole program, so the reference stays valid while it is returned from unwrap_or.
    • Other ways to say it. scores.get(&name).copied().unwrap_or(0) copies the value out of the Option first, so no * or &0 is needed. map_or(0, |s| *s) works too. Each one returns the same numbers.
    • Never unwrap() here. Calling unwrap() on a None panics, which is exactly what this function must avoid.

    What get returns

    For the map above, get("Ben") returns Some(75) and get("Dan") returns None. The Option is Rust's way of making you decide what a missing key means. Here the lesson decides: a missing name scores 0. unwrap_or writes that decision in one place, instead of an if let or a match with two arms. Both of those would also work, and they are worth reaching for when the missing case needs more than a default value.

    Edge cases and common mistakes

    • Missing name. "Dan" is not a key, so get gives None and the function returns 0.
    • Empty map. There are no keys, so every lookup returns 0.
    • Case matters. With the map above, "ana" returns 0 because only "Ana" is a key.
    • A stored score of 0. Scores run from 0 to 100, so a real 0 and a missing name both give 0. The function doesn't need to tell them apart, but get alone would: Some(0) against None.
    • Forgetting the *. Without it the function returns a &i32 where an i32 is expected, and the code doesn't compile.

    Testing

    • {"Ana": 90, "Ben": 75, "Cara": 88} with "Ben" gives 75.
    • The same map with "Dan" gives 0.
    • The same map with "ana" gives 0.
    • An empty map with "Ana" gives 0.
    Keep going with Rust1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free