Closing Channels

Closing a channel indicates that no more values will be sent. This is useful for communicating to receivers that they should stop waiting for new data.

Closing

Only the sender should close a channel.

ch := make(chan int)
// ... send data ...
close(ch)

Checking for Closure

Receivers can use the “comma ok” idiom to check if a channel is closed.

v, ok := <-ch
if !ok {
    // Channel is empty AND closed
}

Key Rules

  1. Send Panics: Sending to a closed channel causes a panic.
  2. Double Close: Closing a channel twice causes a panic.
  3. Receive Zero Values: Receiving from a closed, empty channel immediately returns the zero value for that type and sets ok to false.
  4. Garbage Collection: You don’t have to close channels. If they aren’t being used and can’t be reached, they will be garbage collected. Only close them to signal the receiver.