[ACCEPTED]-golang - Why ++ and -- not work in expressions?-go
++
and --
are statements in golang, not expressions
0
Specifically, ++
and --
are statements because 6 it can be very difficult to understand the 5 order of evaluation when they're in an expression.
Consider 4 the following:
// This is not valid Go!
x := 1
x = x++ + x
y := 1
y = ++y + y
What would you expect x
to 3 be? What would you expect y
to be? By contrast, the 2 order of evaluation is very clear when this 1 is a statement.
Just to help clarify, an expression has 7 a =
, :=
or +=
in them. A statement (such as ++
and 6 —
) does not. See https://stackoverflow.com/a/1720029/12817546.
package main
import "fmt"
var x int
func f(x int) {
x = x + 1 //expression
x++ //statement
fmt.Println(x) //2
}
func main() {
f(x) //expression statement
}
An "expression" specifies 5 the computation of a value by applying operators 4 and functions to operands. See https://golang.org/ref/spec#Expressions.
A "statement" controls 3 execution. See https://golang.org/ref/spec#Statements.
An "expression statement" is 2 a function and method call or receive operation 1 that appears in a statement. See https://golang.org/ref/spec#Expression_statements.
More Related questions
We use cookies to improve the performance of the site. By staying on our site, you agree to the terms of use of cookies.