Explanation of Effective Go if statement

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

Explanation of Effective Go if statement

问题

我正在为您翻译以下内容:

我正在阅读《Effective Go》页面,遇到了以下内容。

最后,Go语言没有逗号运算符,++和--是语句而不是表达式。因此,如果你想在for循环中运行多个变量,你应该使用并行赋值(尽管这样就不能使用++和--)。

// 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。我不理解这部分以及条件中的其他部分。

谢谢 Explanation of Effective Go if statement

英文:

I was reading through the effective go page and I came accross the following.

> 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]
> }

If someone could explain and break down what is going on in this for loop that would be so helpful.

I understand i, j := 0 declares the variables i and j, but why is there a commar followed by len(a)-1. I don't understand that part along with the some other parts in the condition.

Thank you Explanation of Effective Go if statement

答案1

得分: 3

i 被赋予初始值 0,j 被赋值为 len(a)-1。每次循环迭代时,i 会递增,j 会递减,同时从两端索引数组,并交换它们的值。

这个例子利用了 Go 语言的将多个表达式的值分配给多个左值的能力

英文:

i is assigned an initial value of 0, and j is assigned len(a)-1. i will be incremented and j will be decremented by one for each loop iteration, indexing the array from both ends simultaneously, and swapping their values.

This example makes use of Go's ability to assign the values of multiple expressions to multiple Lvalues.

答案2

得分: 2

@nothingmuch的分析是正确的,但我一点也不喜欢这段代码。我喜欢Go语言的一个特点就是缺乏巧妙的一行代码。我觉得如果稍微展开一点,整个代码段会更易读:

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

@nothingmuch's analysis is correct, but I do not like this snippet at all. One of the features I like about go is the lack of clever one liners. I feel like this whole snippet would be much more readable if spread out a little further:

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

huangapple
  • 本文由 发表于 2016年10月27日 09:02:43
  • 转载请务必保留本文链接:https://go.coder-hub.com/40274459.html
匿名

发表评论

匿名网友

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

确定