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

Direct to your inbox, daily. I respect your privacy .

Unsure? Browse the archive .

Related Content


Close

Today we’re looking at the close built-in function. There’s not really any new information here, as we’ve already talked about channels, but it’s a good opportunity to review. Close For an argument ch with a core type that is a channel, the built-in function close records that no more values will be sent on the channel. It is an error if ch is a receive-only channel. Sending to or closing a closed channel causes a run-time panic.


Go statements, conclusion

Today we finish the description of go statements: Go statements … When the function terminates, its goroutine also terminates. If the function has any return values, they are discarded when the function completes. go Server() go func(ch chan<- bool) { for { sleep(10); ch <- true }} (c) Okay, so that bit about discarding return values makes sense, right? func main() { go sum(1, 3) // return value discarded } func sum(a, b int) int { return a + b } But what if you need that return value for something?


Three ways to return values

Return statements … There are three ways to return values from a function with a result type: Do you know all three off the top of your head? We’ll be looking at each of them over the coming three days. The return value or values may be explicitly listed in the “return” statement. Each expression must be single-valued and assignable to the corresponding element of the function’s result type. func simpleF() int { return 2 } func complexF1() (re float64, im float64) { return -7.

Get daily content like this in your inbox!

Subscribe