IncDec statements

April 17, 2024

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.

IncDecStmt = Expression ( "++" | "--" ) .

Most commonly you’ll see ++ and -- used on a simple variable. But as explained, it’s not strictly limited to that. These operators can be used on any addressable (numeric) expression. That means the following is valid:

var i int
f := func() *int {
	return &i
}
*f()++

See it in the playground.

The following assignment statements are semantically equivalent:

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

I’ll add that these are also equivalent to x = x + and x = x - 1 respectively.

Quotes from The Go Programming Language Specification Language version go1.22 (Feb 6, 2024)


Share this

Direct to your inbox, daily. I respect your privacy .

Unsure? Browse the archive .

Get daily content like this in your inbox!

Subscribe