Channels Intro

View saved

Make a channel

Channels carry a typed stream of values. Unbuffered sends wait for a receiver.

ch := make(chan string)

go func() {
	ch <- "ping"
}()

msg := <-ch
fmt.Println(msg)

Buffered channels

A buffer lets sends proceed until the buffer is full.

ch := make(chan int, 2)
ch <- 1
ch <- 2
fmt.Println(<-ch, <-ch)

Close and range

Close a channel when no more values will be sent. Receivers can range until closed.

ch := make(chan int)
go func() {
	for i := 1; i <= 3; i++ {
		ch <- i
	}
	close(ch)
}()
for n := range ch {
	fmt.Println(n)
}

Channel tips

  • Only the sender should close a channel
  • Receiving from a closed channel yields the zero value
  • Select lets you wait on multiple channel operations
  • Start simple: one producer, one consumer

Comments

One comment per signed-in account. Comments are saved with this page’s URL.