以下代码在 Go 1.6 或 1.7 中会产生一个语法错误(unexpected++ at end of statement):
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
关于go - 速记返回,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39280447/