In go docs there is a shuffle example (link)
I've added some output to it as follows:
package main
import (
"fmt"
"math/rand"
"strings"
)
func main() {
words := strings.Fields("ink runs from the corners of my mouth")
fmt.Println(words)
rand.Shuffle(len(words), func(i, j int) {
fmt.Println("Before:", i, j, words[i])
words[i], words[j] = words[j], words[i]
fmt.Println("After:", i, j, words[i])
})
fmt.Println(words)
}
What I would like to understand is the line that has:
words[i], words[j] = words[j], words[i]
And specifically why the output before and after that statement is different. How is this evaluated? Thanks.
The Go Programming Language Specification
A tuple assignment assigns the individual elements of a multi-valued operation to a list of variables. There are two forms. In the first, the right hand operand is a single multi-valued expression such as a function call, a channel or map operation, or a type assertion. The number of operands on the left hand side must match the number of values. For instance, if f is a function returning two values,
x, y = f()
assigns the first value to x and the second to y. In the second form, the number of operands on the left must equal the number of expressions on the right, each of which must be single-valued, and the nth expression on the right is assigned to the nth operand on the left:
one, two, three = '一', '二', '三'
words[i], words[j] = words[j], words[i]
is the second form of a Go tuple assignment. The values of words[i]
and words[j]
are swapped.
words[i], words[j] = words[j], words[i]
becomes:
// on the left
tj := words[j]
ti := words[i]
// on the right
words[i] = tj
words[j] = ti
simplify:
t := words[i]
words[i] = words[j]
words[j] = t