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
- Call
get(&name). The result is anOption<&i32>. - Call
unwrap_or(&0). It returns the reference insideSome, or the default you pass when the option isNone. The default must be a reference too, so it is&0. - Dereference with
*. The expression is now a&i32, and the function returns ani32.
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)isOption<&i32>.unwrap_or(&0)turns it into&i32. The leading*applies to that whole call chain and gives the plaini32. Scores are small, copyable numbers, so copying one out of the reference is cheap. - A reference to a literal.
&0may look odd. Rust lets the compiler keep that constant alive for the whole program, so the reference stays valid while it is returned fromunwrap_or. - Other ways to say it.
scores.get(&name).copied().unwrap_or(0)copies the value out of theOptionfirst, so no*or&0is needed.map_or(0, |s| *s)works too. Each one returns the same numbers. - Never
unwrap()here. Callingunwrap()on aNonepanics, 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, sogetgivesNoneand 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
getalone would:Some(0)againstNone. - Forgetting the
*. Without it the function returns a&i32where ani32is 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.
