Hi
I have been learning Go and have come to a point where I am learning about maps.
I am little confused about the line “frequency[t]++” in the code below, it seems to add the number of times a temperature entry appears in the slice. But how to “read this syntax”. Is this explained in any of online Go resources ?
temperatures := []float64{
-28.0, 32.0, -31.0, -29.0, -23.0, -29.0, -28.0, -33.0,
}
frequency := make(map[float64]int)
for _, t := range temperatures {
frequency[t]++
}
for t, num := range frequency {
fmt.Printf("%+.2f occurs %d times\n", t, num)
}
The instruction frequency[t]++ increments the entry of the map frequency with key t. The map will hold counters of occurence of the different temperature. When t is not yet in the map, a new entry is created with the default value which is 0 for integer. And this value is incremented and becomes 1.
That’s very interesting. I didn’t know it was possible increment a map value in this way. Thanks. I learned something.
My question was more around the seemingly ‘magic behaviour’ around the Map where the “value” against a “temperature” key corresponds to the number of times it occurs.