Understand the contract
Closing a channel tells receivers that no more values will be sent. Buffered values remain available, and a range loop stops after consuming them. The sender or coordinating owner should close the channel when all sends are complete. A receiver generally cannot know whether another sender is still active.
A receive can return value, ok. ok is true for an actual sent value and false once the channel is closed and drained. The value is then the element type’s zero value. This is how a receiver distinguishes a sent zero from completion without reserving a special data value.
Work through the example
The example puts two values into a buffer, closes it and ranges over the remaining data. The final receive prints 0 false. No goroutine is needed to demonstrate drainage because the two sends fit the buffer. A streaming producer would commonly close after its loop returns.
package main
import "fmt"
func main() {
values := make(chan int, 2)
values <- 10
values <- 20
close(values)
for value := range values { fmt.Println(value) }
value, ok := <-values
fmt.Println(value, ok)
}Watch this boundary
Sending to a closed channel panics, as does closing an already closed or nil channel. A nil channel blocks on send and receive. Closing is a completion signal for receivers, not a command that automatically cancels every worker. Use a separate cancellation mechanism when work should stop early.
Practice with a changed input
Include zero among the buffered values and observe that range still receives it. Then write down who would close a channel shared by several producers after a WaitGroup finishes.
Lesson 45 of 50
View the full Go basics seriesReferences & further reading
Need help with your Go backend?
I work with engineering teams on focused Go and Kubernetes platform engagements, with limited consulting availability.
Explore Go consulting services