May 19, 2023
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
// ch must be of type `chan T` or `chan<- T`. A receive-only channel (`<-chan T`) cannot be closed. close(ch)
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
Type identities of other types
Type identity … Two pointer types are identical if they have identical base types. Given: type ( P = *int Q = P R *int ) P, Q, and *int are all identical to each other, but different from *int32 and R. Two function types are identical if they have the same number of parameters and result values, corresponding parameter and result types are identical, and either both functions are variadic or neither is.
I’ve made the case that channels are just data types, and non-magical. So why should we care about channels, rather than just using some sort of slice, array, or custom first-in-first-out queue? The reason is that channels provide us certain guarantees with regard to synchronization. The spec explains: Channel types … A single channel may be used in send statements, receive operations, and calls to the built-in functions cap and len by any number of goroutines without further synchronization.
Channel types … A new, initialized channel value can be made using the built-in function make, which takes the channel type and an optional capacity as arguments: make(chan int, 100) Here we have the semi-magical make built-in function again. We’ve already seen it for use with arrays and slices. Consider this yet another clue that a channel is just another type, similar to array and slice, in that it “just” holds a bunch of values, and isn’t magical in any way.
Improve your knowledge of Go