在Go语言中,函数参数中的后增运算符是不可能的。

huangapple go评论81阅读模式
英文:

Post-increment operator in function argument in Go, not possible?

问题

在Go语言(1.2.1)中,为什么这段代码可以运行?

package main

import (
	"fmt"
)

func main() {
	var i = 0
	for i < 10 {
		fmt.Println(i)
		i++
	}
}

但是这段代码(在函数参数中使用递增运算符)不能运行?

package main

import (
	"fmt"
)

func main() {
	var i = 0
	for i < 10 {
		fmt.Println(i++)
	}
}
英文:

How come, in Go (1.2.1), this works?

package main

import (
	&quot;fmt&quot;
)

func main() {
	var i = 0
	for i &lt; 10 {
		fmt.Println(i)
		i++
	}
}

But this (with the increment operator in the function argument) doesn't?

package main

import (
	&quot;fmt&quot;
)

func main() {
	var i = 0
	for i &lt; 10 {
		fmt.Println(i++)
	}
}

答案1

得分: 36

在Go语言中,i++是一个语句,而不是一个表达式。因此,你不能在另一个表达式中使用它的值,比如函数调用。

这消除了后增量和前增量之间的区别,这是造成混淆和错误的一个来源。

英文:

In Go, i++ is a statement, not an expression. So you can't use its value in another expression such as a function call.

This eliminates the distinction between post-increment and pre-increment, which is a source of confusion and bugs.

huangapple
  • 本文由 发表于 2014年4月24日 06:52:22
  • 转载请务必保留本文链接:https://go.coder-hub.com/23256672.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定