Help understanding this map behaviour

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)
    }

Thanks in advance

Increment and Decrement operations are explained in the Spec (low level):

https://golang.org/ref/spec#IncDec_statements

Not sure if there is a higher level explanation available somewhere.

Also, this isn’t related to maps, increment and decrement operators work with any numeric data type (or whas it only integral?).

1 Like

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.

1 Like

Thanks @NobbZ.

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.

But it is now clear from @Christophe_Meessen’s explanation

Thanks for your explanation @Christophe_Meessen. It makes sense now.

Indeed, a very compact statement to find the ‘frequency’ of a value in a list!

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.