×

go · level 3 · unit 2 · lesson 2

  1. meet it
  2. guess first
  3. your turn
  4. fix it
  5. nailed it

Tap a green word if you get lost.

meet it

A holds a few values before anyone waits.

make(chan string, 3) makes a buffered channel with a of 3: room for three values. A send drops its value in and carries on at once, unless the buffer is full; only then does it wait. A receive takes the oldest value, and waits only when the buffer is empty.

len(ch) tells you how many values are waiting and cap(ch) how many fit. Values come out in the order they went in, like a queue at the bakery.

If every goroutine is waiting and none can ever move, the program is stuck for good. That is a , and Go stops it with all goroutines are asleep - deadlock!. A bigger buffer can hide a design mistake, so count your sends and receives first.

package main
import "fmt"
func main() {
	queue := make(chan string, 3)
	queue <- "Ada"
	queue <- "Grace"
	fmt.Println(len(queue), "waiting, room for", cap(queue))
	fmt.Println("Serving", <-queue)
	fmt.Println(len(queue), "waiting")
}

No goroutine is needed here, because both sends fit in the buffer.