Closing channels

May 19, 2023

Channel types

A channel may be closed with the built-in function close. The multi-valued assignment form of the receive operator reports whether a received value was sent before the channel was closed.

Closing a channel is a simple matter of using the built-in close function:

// ch must be of type `chan T` or `chan<- T`. A receive-only channel (`<-chan T`) cannot be closed.
close(ch)

Calling close on a channel takes immediate effect, and prevents further values from being written to the channel (any items already in the channel may still be read). Attempting to write to a closed channel will cause a runtime panic.

Attempting to read from a closed channel will return in the zero value of the channel’s type. To detect that the channel is closed while reading, you may use the two-value version of the receive operator, which will return a second value of true if the channel is open, or false if closed.

value, ok := <-ch // ok=true if ch is open, false if closed

Quotes from The Go Programming Language Specification Version of December 15, 2022

Share this