Search code examples
gochannelgoroutine

Receiving values from channels in Go


Why doesn't the last result returned from go sum(s[len(s)/2:], c)(the second one) be assigned to x? The two <-cs confuse me. This code is from A Tour of Go - [Channels].

package main

import "fmt"

func sum(s []int, c chan int) {   // int is the return value type
  sum := 0
  for _, v := range s {
    sum += v
  }
  c <- sum // Sends sum to c
}

func main() {
  s := []int{7, 2, 8, -9, 4, 0}

  c := make(chan int)
  go sum(s[:len(s)/2], c)
  go sum(s[len(s)/2:], c)

  x, y := <-c, <-c                 // receive from c

  fmt.Println(x, y, x+y)
}

Solution

  • Do you mean this line?

    x, y := <-c, <-c
    

    That's a "tuple assignment".

    In this case, it would be equivalent to doing:

    x := <-c
    y := <-c
    

    So the second value read from c would be assigned to y.

    You can read more about it here:

    https://golang.org/ref/spec#Assignments

    About the order in which the values are actually written to c, since two independent goroutines are being triggered here:

    go sum(s[:len(s)/2], c)
    go sum(s[len(s)/2:], c)
    

    The order in which they end up processing and writing to c is not "guaranteed", so you can expect either one of the values be assigned to x and y in different runs.

    Since the values are being added to calculate the final result, this is not a problem in this case.