Coming from PHP, I got used to using the increment (++) and decrement (–) operators in lots of different ways as it is quite flexible in PHP. PHP allows the operators to be used on variables in both a prefix and postfix notations as well as an expression.
Golang, on the other hand, is a lot more restrictive as it only supports the postfix notation.
i := 0 fmt.Println(++i) fmt.Println(i++)
Both of these
Println statements fail with syntax errors.
./main.go:7:14: syntax error: unexpected ++, expecting expression ./main.go:8:15: syntax error: unexpected ++, expecting comma or )
In Golang, the operators cannot be expressions and instead can only be used as statements. The operators can also only be used as postfix operators
It perhaps seems silly to not support having these operators as expressions while Golangs design choice makes for a much simpler syntax and evaluation.
The snipper above can be updated with a simple change to make it work.
i := 0 i++ fmt.Println(i) fmt.Println(i) i++
Below is a quote from the Go FAQ explaining the reasoning behind this decision.
Why are ++ and – statements and not expressions? And why postfix, not prefix?
Without pointer arithmetic, the convenience value of pre- and postfix increment operators drops. By removing them from the expression hierarchy altogether, expression syntax is simplified and the messy issues around order of evaluation of ++ and – (consider f(i++) and p[i] = q[++i]) are eliminated as well. The simplification is significant. As for postfix vs. prefix, either would work fine but the postfix version is more traditional; insistence on prefix arose with the STL, a library for a language whose name contains, ironically, a postfix increment.