Shorthand return in Go (golang)

前端 未结 2 842
时光说笑
时光说笑 2021-01-23 17:28

The following code generates a syntax error (unexpected ++ at end of statement) in Go 1.6 or 1.7:

package main

import \"fmt\"

var x int

func          


        
相关标签:
2条回答
  • 2021-01-23 18:12

    It's an error, because the ++ and -- in Go are statements, not expressions: Spec: IncDec Statements (and statements have no results that would be returned).

    For reasoning, see Go FAQ: 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.

    So the code you wrote can only be written as:

    func increment() int {
        x++
        return x
    }
    

    And you have to call it without passing anything:

    fmt.Println(increment())
    

    Note that we would be tempted to still try to write it in one line using an assignment, e.g.:

    func increment() int {
        return x += 1 // Compile-time error!
    }
    

    But this also doesn't work in Go, because the assignment is also a statement, and thus you get a compile-time error:

    syntax error: unexpected += at end of statement

    0 讨论(0)
  • 2021-01-23 18:27

    The accepted solution is right that the OP's code does not work because in go increment/decrement(x++/x--) statements are expressions that don't return a value.

    However the solution presented has a slightly different effect than the original request.

    x++ would return the value of x then increment in C like syntax.

    however the opposite would happen if you do it this way:

    x++
    return x
    

    You can negate that issue by reducing your initial value by one or by using a defer statement as written here:

    func incr() int {
        defer func() { counter++ }()
        return counter
    }
    

    https://play.golang.org/p/rOuAv7KFJQw

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