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 functionclose
records that no more values will be sent on the channel. It is an error ifch
is a receive-only channel. Sending to or closing a closed channel causes a run-time panic. Closing thenil
channel also causes a run-time panic. After callingclose
, and after any previously sent values have been received, receive operations will return the zero value for the channel’s type without blocking. The multi-valued receive operation returns a received value along with an indication of whether the channel is closed.
I think the most important thing to rember about close
, is that it only directly affects send operations.
That is to say, if you have a (buffered) channel with a number of unread elements in it, calling close
will not affect those elements—they can still be read.
ch := make(chan int, 10)
ch <- 1
ch <- 2
ch <- 3
close(ch)
for i := range ch {
fmt.Println("read value:", i)
}
Quotes from The Go Programming Language Specification Language version go1.23 (June 13, 2024)