A Brief Analysis of parallel assignment in golang

  • 2020-06-15 09:16:01
  • OfStack

For golang, swapping two Numbers is easy, as follows:


i, j = j, i

The left-hand side and the right-hand side contain multiple expressions, which are parallel assignments. Assignment is divided into two steps:

Evaluates the index expression and addressing expression of the operands to the left of the equal sign, and evaluates the expression to the right of the equal sign. The assignment

So let's look at what's going to come out of this 1 piece of code.


func main() {
 i := 1
 s := []string{"A", "B", "C"}
 i, s[i-1] = 2, "Z"
 fmt.Printf("s: %v \n", s)
}

s: [Z,B,C] instead of s: [A,Z,C]. This is because the index expression i-1 for the slice to the left of the equal sign is evaluated first and assigned last. The order of calculation and assignment is left to right. Now, what does the following code output?


func main() {
 a := []int{1, 2, 3, 4}
 defer func(a []int) {
  fmt.Printf("a: %v\n", a)
 }(a)
 a[0], a[4] = a[1], a[2]
}

The output is:


a: [2 2 3 4]
panic: runtime error: index out of range

goroutine 1 [running]:

During the assignment, even if the latter raises panic, the former is assigned successfully. Now what does this output?


func main() {
 a := []int{1, 2, 3, 4}
 defer func(a []int) {
  fmt.Printf("a: %v\n", a)
 }(a)
 a[0], a[1] = a[2], a[4]
}

The output is:


a: [1 2 3 4]
panic: runtime error: index out of range

goroutine 1 [running]:
main.main()

Again, the first step of the assignment is to evaluate the index expression to the left of the equals sign, the address expression and the expression to the right of the equals sign.

Refer to Go Concurrent Programming 1 Book for understanding

conclusion


Related articles: