英文:
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 := "abcde"
r := []rune(s)
for i, j := 0, len(s)-1; i < j; i, j = i++, j-- {
r[i], r[j] = r[j], r[i]
}
fmt.Printf("%s\n", 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)++.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论