golang - Why ++ and — not work in expressions?

前端 未结 3 407
清酒与你
清酒与你 2021-01-26 12:45

What we take for granted in other languages and almost expect it to work in go, won\'t work - its almost so natural to do this, so why isn\'t the compiler happy? Just feeling li

相关标签:
3条回答
  • 2021-01-26 13:20

    Specifically, ++ and -- are statements because it can be very difficult to understand the order of evaluation when they're in an expression.

    Consider the following:

    // This is not valid Go!
    x := 1
    x = x++ + x
    y := 1
    y = ++y + y
    

    What would you expect x to be? What would you expect y to be? By contrast, the order of evaluation is very clear when this is a statement.

    0 讨论(0)
  • 2021-01-26 13:33

    Just to help clarify, an expression has a =, := or += in them. A statement (such as ++ and ) 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 the computation of a value by applying operators and functions to operands. See https://golang.org/ref/spec#Expressions.

    A "statement" controls execution. See https://golang.org/ref/spec#Statements.

    An "expression statement" is a function and method call or receive operation that appears in a statement. See https://golang.org/ref/spec#Expression_statements.

    0 讨论(0)
  • 2021-01-26 13:35

    ++ and -- are statements in golang, not expressions

    0 讨论(0)
提交回复
热议问题