Problem overview
The function safeLookup receives scores, a map[string]int from names to scores, and a name. It returns the score of name, or 0 when name isn't a key. The map may be empty, and keys match exactly, so "ana" is not "Ana".
With {"Ana": 90, "Ben": 75, "Cara": 88}, the name "Ben" gives 75 and "Dan" gives 0. With an empty map, any name gives 0.
Approach
A plain scores[name] already returns 0 for a missing key, because Go gives the zero value of the value type, and the zero value of int is 0. That alone would pass here, but it can't tell a missing name from a name whose score really is 0. Go answers that with a two-value lookup:
score, ok := scores[name]
ok is a bool: true if name is a key, false if not. For "Dan" in the map above, score is 0 and ok is false. For a key stored with the value 0, such as "Zoe" in {"Zoe": 0}, score is 0 and ok is true.
Step by step
- Look up and test in one
if. Go lets anifstart with a short statement, soif score, ok := scores[name]; okdoes the lookup and checksok. Inside the block, returnscore. - Return 0 after the
if. Execution only gets there when the name wasn't found, because thereturninside the block has already ended the function otherwise.
The solution in Go
func safeLookup(scores map[string]int, name string) int {
if score, ok := scores[name]; ok {
return score
}
return 0
}
Notes on the Go details:
- Scope.
scoreandokexist only inside theifstatement. That keeps them from leaking into the rest of the function. - Unused variables are errors. Both are used,
okin the condition andscorein the return. If you only needed to know whether a key exists, write_, ok := scores[name]. - Why the check is better than the shortcut. The explicit check spells out the intent, and the default can be anything: replacing
return 0withreturn -1changes the missing-key answer without touching the lookup. The shortcut can only produce the zero value.
The two-value form works with any value type, which is where it matters. For a map[string]string, the zero value is the empty string, and for a map[string]bool it is false. If a name could really have the score 0, the check is the only way to tell "not in the map" from "stored as 0". Here the scores are between 0 and 100, so a stored 0 and a missing name both give 0 and the check changes nothing in the result.
Edge cases and common mistakes
- Empty map. A lookup in
{}is fine:okisfalseand the function returns 0. - Case sensitivity.
safeLookup(scores, "ana")returns 0 when only"Ana"is a key. - Returning inside the wrong place. Putting
return 0inside theifblock would return 0 for every name that exists.
Testing
{"Ana": 90, "Ben": 75, "Cara": 88},"Ben"gives 75.- The same map with
"Dan"gives 0. {}with"Ana"gives 0.- The same map with
"ana"gives 0.
