英文:
golang - Why ++ and -- not work in expressions?
问题
在其他语言中,我们认为理所当然的事情,并且几乎期望它在Go语言中也能正常工作,但实际上并不会——这样做几乎是自然而然的,那么为什么编译器不满意呢?有时候我真的想放弃Go语言。
唯一增加值的方法是将其放在单独的一行中吗?
package main
import "fmt"
import "strconv"
func main() {
a := 1
//计算表达式并传递给函数——不起作用
fmt.Println(strconv.Itoa(a++))
//在a++周围加上括号也不起作用
fmt.Println(strconv.Itoa((a++)))
}
链接:http://play.golang.org/p/_UnpZVSN9n
英文:
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 like bailing out of go sometimes.
The only way to increment the value is to put it in its own separate line?
http://play.golang.org/p/_UnpZVSN9n
package main
import "fmt"
import "strconv"
func main() {
a := 1
//Evaluate expression and pass into function - won't work
fmt.Println(strconv.Itoa(a++))
//Braces around a++ also won't work
fmt.Println(strconv.Itoa((a++)))
}
答案1
得分: 10
++
和 --
是 golang 中的语句,而不是表达式。
英文:
++
and --
are statements in golang, not expressions
答案2
得分: 1
具体来说,++
和 --
是语句,因为当它们在表达式中时,很难理解它们的求值顺序。
考虑以下代码:
// 这不是有效的 Go 代码!
x := 1
x = x++ + x
y := 1
y = ++y + y
你会期望 x
是多少?你会期望 y
是多少?相比之下,当这是一个语句时,求值顺序是非常清晰的。
英文:
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.
答案3
得分: 0
只是为了帮助澄清,一个表达式中包含=
、:=
或+=
。而语句(如++
和—
)则没有。请参阅https://stackoverflow.com/a/1720029/12817546。
package main
import "fmt"
var x int
func f(x int) {
x = x + 1 // 表达式
x++ // 语句
fmt.Println(x) // 2
}
func main() {
f(x) // 表达式语句
}
"表达式"通过将运算符和函数应用于操作数来指定值的计算。请参阅https://golang.org/ref/spec#Expressions。
"语句"控制执行。请参阅https://golang.org/ref/spec#Statements。
"表达式语句"是出现在语句中的函数和方法调用或接收操作。请参阅https://golang.org/ref/spec#Expression_statements。
英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论