Shorthand return

Shorthand return

以下代码在 Go 1.6 或 1.7 中生成语法错误(语句末尾意外的 ++):

package main

import "fmt"

var x int

func increment() int {
        return x++   // not allowed
}

func main() {
  fmt.Println( increment() )
}

这不应该被允许吗?

这是一个错误,因为 Go 中的 ++-- 是语句,而不是表达式:Spec: IncDec Statements(并且语句没有返回的结果)。

推理参见 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.

所以你写的代码只能写成:

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

而且你必须在不传递任何内容的情况下调用它:

fmt.Println(increment())

请注意,我们仍然会尝试使用赋值将其写在一行中,例如:

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

但这在 Go 中也不起作用,因为 assignment 也是一个语句,因此你会得到一个编译时错误:

syntax error: unexpected += at end of statement

公认的解决方案是正确的,OP 的代码不起作用,因为在 go increment/decrement(x++/x--) 语句中是不 return 值的表达式。

然而,所提供的解决方案与原始请求的效果略有不同。

x++ 会 return x 的值然后像 C 语法一样递增。

然而,如果你这样做会发生相反的情况:

x++
return x

您可以通过将初始值减一或使用此处所写的延迟语句来解决该问题:

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

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