Go Maps - Missing Entry
An interesting snippet
Last time I saw a practice code that calculates the presence of a word in a given sentence and saves the result into a map.
func countForEachWord(s string) map[string]int {
words := strings.Fields(s)
m := make(map[string]int)
for _, w:= range words {
m[w]++
}
return m
}
I was like, “Why it doesn’t have to check the existence of each entry?”
“comma ok” idiom
Effective Go shows us the idiomatic way to distinguish a missing entry from a zero value by using “comma ok” idiom.
var studentsScores := map[string]int{
"Anna": 100,
"Bill": 80,
}
func getScore(name string) int {
if score, ok := studentsScores[name]; ok {
return score
}
fmt.Printf("There isn't a score for %s\n", name)
return 0
}
Let’s find the answer!
Index expressions
Let’s check the spec
For a of map type M:
- x’s type must be assignable to the key type of M
- if the map contains an entry with key x, a[x] is the map element with key x and the type of a[x] is the element type of M
- if the map is nil or does not contain such an entry, a[x] is the zero value for the element type of M
Oh, that’s why the code adds the value directly without checking the existence of an entry.
The spec tells us that if the map is nil or does not contain such an entry, a[x] is the zero value for the element type of M
.
So the code leverage on the “zero value” characteristic. But I’m not sure whether it’s a good practice or not.
Summary
If the map does not contain such an entry, the index expression gives the zero value for the element type of the map.