I am following the Go tutorial here https://tour.golang.org/moretypes/23 and have modified the exercise a little bit to try to dig deeper.
package main
import (
"fmt"
"strings"
)
func WordCount(s string) map[string]int {
m := make(map[string]int)
x := strings.Fields(s)
for _, e := range x {
m[e]++
}
return m
}
func main() {
phrase := "The quick brown fox"
fmt.Println(WordCount(phrase), "length:", len(WordCount(phrase)))
}
What doesn't make sense to me is how the ++ operator works in this context when adding new elements to the map.
Definition of ++ operator: Increment operator. It increases the integer value by one.
In this context, the ++ operator increasing the integer value of the LENGTH of the map and then adding the e element to the new map length?
The default value of int
values in a map
is 0
. So, when you iterate through x
and call m[e]++
, the expanded version would be
m[e] = m[e] + 1
In other words:
m[e] = 0 + 1
Of course, if a field repeats, it will already be in the map (with some value > 0).
When you check the length of the map after the loop, it gives the number of unique fields in the string.