问题描述
以下代码在Go 1.6或1.7中生成语法错误(语句末尾意外的++ ):
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 increment() int {
return x++ // not allowed
}
func main() {
fmt.Println( increment() )
}
这是不允许的吗?
推荐答案
这是一个错误,因为Go中的 ++
和-
是语句,而不是表达式:规范:IncDec语句(并且该语句没有将返回的结果).
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).
有关推理的信息,请参阅Go常见问题解答:为什么++和-语句而不是表达式?为何使用后缀而不是前缀?
For reasoning, see Go FAQ: Why are ++ and -- statements and not expressions? And why postfix, not prefix?
所以您编写的代码只能写为:
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!
}
但这在Go中也不起作用,因为分配也是一个声明,因此您会得到一个编译时错误:
But this also doesn't work in Go, because the assignment is also a statement, and thus you get a compile-time error:
这篇关于速记回报的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!