gpt4 book ai didi

go - Go编程语言中的for循环

转载 作者:IT王子 更新时间:2023-10-29 01:43:11 25 4
gpt4 key购买 nike

我正在编写一个函数来使用 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))
}

然而,编译器提示 i, j = i++, j-- 说,语法错误:意外的++,期待 {

如果我将其更改为 i, j = i+1, j-1,则该函数有效。我不知道为什么这是不允许的。任何人都可以帮忙吗?谢谢你。

最佳答案

在 Go 中,x--x++ 是语句,而不是表达式,所以你不能那样给它们赋值,这是设计使然。

Spec说:

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)++.

关于go - Go编程语言中的for循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24716779/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com