When I take the tour of Golang from golang.org, there's one code snippet I don't understand:
func sum(a []int, c chan int, order int) {
sum := 0
for _, v := range a {
sum += v
}
fmt.Println(order, a)
c <- sum // 将和送入 c
}
func main() {
a := []int{7, 2, 8, -9, 4, 0}
c := make(chan int)
a1, a2 := a[:len(a)/2], a[len(a)/2:]
go sum(a1, c, 1)
x := <-c
go sum(a2, c, 2)
y := <-c
//x := <-c
//y := <-c
// x, y := <-c, <-c // 从 c 中获取
fmt.Println(x, y, x+y)
}
This is the output I expected:
1 [7 2 8]
2 [-9 4 0]
17 -5 12
and when I changed the code:
func main() {
a := []int{7, 2, 8, -9, 4, 0}
c := make(chan int)
a1, a2 := a[:len(a)/2], a[len(a)/2:]
go sum(a1, c, 1)
//x := <-c
go sum(a2, c, 2)
//y := <-c
x := <-c
y := <-c
// x, y := <-c, <-c // 从 c 中获取
fmt.Println(x, y, x+y)
}
Why is the output like this:
2 [-9 4 0]
1 [7 2 8]
-5 17 12