Junior — Middle
How to ensure that a channel in the system is already closed?
sobes.tech AI
Answer from AI
In Go, you can determine if a channel is closed by attempting to read from it. When reading from a closed channel, the operation does not block and returns the zero value and a flag indicating that the channel is closed.
Example:
ch := make(chan int)
close(ch)
v, ok := <-ch
if !ok {
fmt.Println("Channel is closed")
} else {
fmt.Println("Received value", v)
}
Here, ok will be false if the channel is closed. This is the standard way to check the state of a channel in Go.