Effective Go if 语句详解

Explanation of Effective Go if statement

我在阅读 effective go 页面时发现了以下内容。

Finally, Go has no comma operator and ++ and -- are statements not expressions. Thus if you want to run multiple variables in a for you should use parallel assignment (although that precludes ++ and --).

// Reverse a
for i, j := 0, len(a)-1; i < j; i, j = i+1, j-1 {
    a[i], a[j] = a[j], a[i]
}

如果有人能解释和分解这个 for 循环中发生的事情,那将非常有帮助。

我理解 i, j := 0 声明了变量 i 和 j,但为什么后面有一个逗号 len(a)-1。我不理解该部分以及条件中的其他部分。

谢谢:)

i赋初值0,j赋初值len(a)-1。对于每个循环迭代,i 将递增,j 将递减 1,同时从两端索引数组,并交换它们的值。

这个例子使用了 Go 的 ability to assign the values of multiple expressions to multiple Lvalues.

@nothingmuch 的分析是正确的,但我一点也不喜欢这个片段。我喜欢 go 的一个特点是没有巧妙的单行代码。我觉得如果再展开一点,整个片段会更具可读性:

i := 0
j := len(a) - 1
for i < j {
    a[i], a[j] = a[j], a[i]
    i++
    j--
}