Reputation: 12531
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 :)
Upvotes: 1
Views: 157
Reputation: 23108
@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 < j {
a[i], a[j] = a[j], a[i]
i++
j--
}
Upvotes: 2
Reputation: 1516
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.
Upvotes: 3