Go编程语言中的for循环

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

For loop in Go programming language

问题

我正在编写一个使用Go语言反转字符串的函数。

func main() {
    s := "abcde"
    r := []rune(s)
    for i, j := 0, len(s)-1; i < j; i, j = i+1, j-1 {
        r[i], r[j] = r[j], r[i]
    }
    fmt.Printf("%s\n", string(r))
}

然而,编译器报错了i, j = i++, j--,提示syntax error: unexpected ++, expecting {

如果我将其改为i, j = i+1, j-1,这个函数就可以正常工作了。
我不知道为什么不允许使用i++j--。有人可以帮忙解释一下吗?
谢谢。

英文:

I am writing a function to reverse a string using Go.

func main() {
	    s := &quot;abcde&quot;
	    r := []rune(s)
	    for i, j := 0, len(s)-1; i &lt; j; i, j = i++, j-- {
		       r[i], r[j] = r[j], r[i]
	    }
	fmt.Printf(&quot;%s\n&quot;, string(r))
}

However, the compiler complaints about i, j = i++, j--, says,
syntax error: unexpected ++, expecting { .

This function works if i change that into i, j = i+1, j-1.
I don't know why this isn't allowed. Anyone can help?
Thank u.

答案1

得分: 2

在Go语言中,x--x++是语句而不是表达式,所以你不能像那样对它们进行赋值,这是有意设计的。

规范中指出:

一元操作符具有最高的优先级。由于++和--操作符是语句而不是表达式,它们不属于操作符层次结构。因此,语句*p++等同于(*p)++。

英文:

In Go, x-- and x++ are statements, not expressions, so you can't assign them like that, and it's by design.

The Spec says:

>Unary operators have the highest precedence. As the ++ and -- operators form statements, not expressions, they fall outside the operator hierarchy. As a consequence, statement *p++ is the same as (*p)++.

huangapple
  • 本文由 发表于 2014年7月13日 03:56:01
  • 转载请务必保留本文链接:https://go.coder-hub.com/24716779.html
匿名

发表评论

匿名网友

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

确定