Sobes.tech
Junior — Middle

Is it permissible to get information from a channel with a set closed mode?

sobes.tech AI

Answer from AI

In Go, if a channel is closed, you can continue to receive data from it until the channel buffer is empty. After all data has been read, further read operations from the closed channel return the zero value of the channel's type and a flag indicating that the channel is closed.

That is, it is permissible to receive information from a closed channel, but you need to check the second return value to understand whether there is still data or the channel is completely empty.

Example:

data, ok := <-ch
if !ok {
    // channel is closed and empty
}

Attempting to send data to a closed channel will cause a panic.