Closing a channel

Closing a channel indicates that its sender has finished producing values and will not send any more. Receivers can consume values already buffered, and ranging over the channel terminates after it is closed and drained.

Minimal example

go
events := make(chan string, 2)
events <- "accepted"
events <- "dispatched"
close(events)
for event := range events {
    fmt.Println(event)
}

Learn this concept

Lesson 5.1 · Channels, select and cleanup

Used in exercises

Exercise 5.3 · Per-user WebSocket hub
Prerequisite conceptsChannelsBuffered channel