Junior — Middle
What are the ways to manage or interact with a closed channel in Go?
sobes.tech AI
Answer from AI
In Go, a closed channel (unbuffered channel) is a channel without a buffer that synchronizes the sender and receiver. You can manage or interact with such a channel in the following ways:
- Sending and receiving: The sender blocks until the receiver reads the value, and vice versa.
- Closing the channel: You can close a channel using the
close(channel)function. After closing, you cannot send values, but you can read remaining values and receive zero values. - Checking if closed: When reading from a channel, you can check if it is closed using the second parameter:
v, ok := <-ch
if !ok {
// channel is closed
}
- Using select: For non-blocking interactions or timeouts, you can use the
selectstatement with channels.
Example:
ch := make(chan int) // closed channel
// Sending
go func() {
ch <- 42
}()
// Receiving
val := <-ch
// Closing
close(ch)
// Checking
v, ok := <-ch
if !ok {
fmt.Println("Channel is closed")
}