Is ++ syntactic sugar for += 1?

Issue

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?

Solution

The language specification says that the ++/– operators should work with a map index expression as the operand.

https://go.dev/ref/spec#IncDec_statements

The "++" and "–" statements increment or decrement their operands by
the untyped constant 1. As with an assignment, the operand must be
addressable or a map index expression.

How that functionality should be implemented is not specified and may therefore be different across different compilers or different versions of the same compiler.


If you search the cmd/compile/internal directory of your Go installation, which is the source code of the Go compiler if I’m not mistaken, you’ll find a number of lines that seem to confirm your guess. I have nowhere near enough knowledge about the code to provide a conclusive answer however.

Examples: one and two

And the gccgo implementation of the spec, which I’ve never looked at, may or may not do the IncDec the same way.

Answered By – mkopriva

Answer Checked By – Mildred Charles (GoLangFix Admin)

Leave a Reply

Your email address will not be published.