Channels

Channels are a typed conduit through which you can send and receive values with the channel operator, <-.

  1. ch <- v // Send v to channel ch.
  2. v := <-ch // Receive from ch, and
  3. // assign value to v.

(The data flows in the direction of the arrow.)

Like maps and slices, channels must be created before use:

  1. ch := make(chan int)

By default, sends and receives block until the other side is ready. This allows goroutines to synchronize without explicit locks or condition variables.

The example code sums the numbers in a slice, distributing the work between two goroutines. Once both goroutines have completed their computation, it calculates the final result.

channels.go

  1. package main
  2. import "fmt"
  3. func sum(s []int, c chan int) {
  4. sum := 0
  5. for _, v := range s {
  6. sum += v
  7. }
  8. c <- sum // send sum to c
  9. }
  10. func main() {
  11. s := []int{7, 2, 8, -9, 4, 0}
  12. c := make(chan int)
  13. go sum(s[:len(s)/2], c)
  14. go sum(s[len(s)/2:], c)
  15. x, y := <-c, <-c // receive from c
  16. fmt.Println(x, y, x+y)
  17. }