Junior — Middle
How does the mechanism of reading data from a closed channel work and what happens at that moment?
sobes.tech AI
Answer from AI
In Go, reading from a channel is an operation that blocks the calling goroutine until data appears in the channel or the channel is closed.
If the channel is closed and there are no more data, reading from it returns the zero value of the channel's type and a flag indicating that the channel is closed. This allows you to determine that no further data will be sent.
Example:
ch := make(chan int)
close(ch)
value, ok := <-ch
if !ok {
fmt.Println("Channel is closed, no more data")
}
Thus, when reading from a closed channel, the goroutine does not block but receives a signal of closure, allowing for proper termination of work with the channel.