Channels

A channel is a typed pipe between goroutines. A send on an unbuffered channel waits until a receive is ready, and a receive waits until a send is ready, so the two goroutines meet at the statement: the value moves and both continue. That rendezvous is the synchronisation, which is why a channel is not a queue that happens to be thread-safe but a way to hand work over.

A value handed over

make(chan string) creates an unbuffered channel of strings. The goroutine sends "ping" and blocks; main receives it and prints. If main received first it would block until the send arrived, so the order of the two statements does not matter: whichever gets there first waits for the other.

package main import "fmt" func main() { messages := make(chan string) go func() { messages <- "ping" }() msg := <-messages fmt.Println("received:", msg) }

go build -o app main.go && ./app

received: ping

The arrow points the way the value travels: messages <- "ping" writes to the channel, <-messages reads from it. A channel of channels and a channel of structs are the same thing; the type after chan is what travels, and a channel of interfaces can carry anything that satisfies the interface.

Close and range

A producer closes the channel when it has nothing more to send, and a receiver can then range over it: the loop takes every value and ends when the channel is closed and drained. The close is a statement about the producer, not about the values, and only the producer should make it. Sending on a closed channel panics; receiving from one returns the zero value at once.

package main import "fmt" func main() { numbers := make(chan int) go func() { defer close(numbers) for i := 1; i <= 3; i++ { numbers <- i * 10 } }() total := 0 for n := range numbers { fmt.Println("got", n) total += n } fmt.Println("total:", total) }

go build -o app main.go && ./app

got 10
got 20
got 30
total: 60

The deferred close runs after the loop, so the range ends exactly when the producer is done. Without the close, the range would block forever after the third value and the program would die with a deadlock; a producer that forgets the close is the most common channel bug.

A channel as a signal

A channel does not have to carry data: a closed or a single sent value is enough to say "done". The worker below takes a send-only channel, chan<- bool, so the compiler refuses a receive in the worker that only produces. Direction in the signature is documentation the compiler enforces.

package main import ( "fmt" "time" ) func worker(done chan<- bool) { fmt.Println("working") time.Sleep(10 * time.Millisecond) done <- true } func main() { done := make(chan bool) go worker(done) if <-done { fmt.Println("work finished") } }

go build -o app main.go && ./app

working
work finished

A bool is a little wasteful for a signal; chan struct{} carries no value at all and costs no memory beyond the channel header. Closing it instead of sending is the usual form, because a closed channel can be selected by any number of receivers and a close can happen only once.

The zero value is nil

A channel that was declared and not made is nil. Its length and capacity are zero, and a send or a receive on it blocks forever, which is occasionally useful: a select with a nil branch never takes that branch. Passing a nil channel to a function that sends is a bug the compiler accepts and the program reports as a deadlock.

package main import "fmt" func main() { var ch chan int fmt.Println("nil:", ch == nil) fmt.Println("len:", len(ch), "cap:", cap(ch)) }

go build -o app main.go && ./app

nil: true
len: 0 cap: 0

The safe default is to make every channel a function receives or sends on. A nil channel is only right when the program wants "no channel here yet" and a select is the thing that reads it.

Exercises

  1. Reverse the order of the send and the receive in the first program: receive in main before starting the goroutine. What happens, and which goroutine is waiting?
  2. Remove the close from the range program and run it. Read the fatal error and name the goroutine the runtime reports.
  3. Change the done channel to chan struct{} and close it instead of sending. What does the receive look like, and why is the zero value all a receiver needs?

Questions

A new set of questions in a new order every time. Choose one answer for each, then check.

  1. What does make(chan string) create?

    Answer

    An unbuffered channel of strings

    The send blocks until a receive is ready.

  2. When does a send on an unbuffered channel return?

    Answer

    When a receiver is ready

    The two goroutines meet at the statement.

  3. What does range over a channel do?

    Answer

    Reads until the channel is closed and empty

    The producer must close it when it is done.

  4. Who should close a channel?

    Answer

    The producer, when it has nothing more to send

    A send on a closed channel panics.

  5. What does a receive from a closed channel return?

    Answer

    The zero value at once

    A two-value receive reports whether the channel is still open.

  6. What does chan<- bool mean in a parameter?

    Answer

    A channel that can only be sent to

    The arrow points towards the channel.

  7. What is the zero value of a channel?

    Answer

    nil

    A send or receive on it blocks forever.

  8. Why prefer chan struct{} for a signal?

    Answer

    It carries no value and costs less

    A signal needs no payload.

  9. What is the root cause of most channel bugs?

    Answer

    A producer that never closes or a receiver that never reads

    A channel that nobody closes or drains blocks its program.

  10. What is the type of messages in make(chan string)?

    Answer

    chan of string

    The element type follows the chan keyword.

The code on this page was run with go 1.26.10 on Alpine Linux 3.24.3 (x86_64) in a Docker container.

Article author: Arthur Isaev