'Is ++ syntactic sugar for += 1?

As far as I understand, indexing a map returns a copy of the map value. With this in mind, consider the following code:

package main

import "fmt"

func main() {
    m := map[string]int{"xxx": 100}
    m["xxx"]++
    fmt.Println(m["xxx"]) // prints 101
}

The code above prints 101, whereas I expected 100. My reasoning is that m["xxx"] returns a copy of the value assigned to the key "xxx" (i.e., 100), and the operator ++ increments this copy of the value but this doesn't affect the original value stored in the map – only the copy changes.

However, considering that we assign a value to a map key by putting the key within brackets and using = to specify the value (i.e., m[key] = value). Then, if m["xxx"]++ were translated to m["xxx"] += 1 by the compiler – which is, in turn, equivalent to m["xxx"] = m["xxx"] + 1 – this would explain the result of the code above.

My question is whether the increment operator (++) is syntactic sugar for the by-one addition assignment (+= 1). Otherwise, what am I missing?

go


Solution 1:[1]

"My reasoning is that m["xxx"] returns a copy of the value" — I don't think this is a fair assumption. The specs under index expressions only say the following:

A primary expression of the form a[x] denotes the element of the [...] map a indexed by x

and

if the map contains an entry with key x, a[x] is the map element with key x

The verbs "denotes" and "is" arguably do not imply a copy. A copy is made only when you assign the result of the index expression to a variable.

The map index expression is simply not addressable, so that you can't memory alias the values stored in the map.

As for whether the increment operator ++ is syntactic sugar for += 1 or not, the specs explicitly state that:

The following assignment statements are semantically equivalent:

IncDec statement    Assignment
x++                 x += 1
x--                 x -= 1

So op++ has the same meaning of op += 1, and a[x]++ increments the operand a[x] which "denotes/is" the map element with key x.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 blackgreen