What happens when reading from a closed channel? Why does the program hang in an infinite loop when reading from a closed channel without range?
sobes.tech AI
Answer from AI
When reading from a closed channel in Go, the read operation returns the zero value of the channel's type and a flag indicating that the channel is closed. If you read from a channel using the construct value, ok := <-ch, then when the channel is closed, ok becomes false, and you can properly handle the end of data.
However, if you read from a channel in an infinite loop without checking ok (for example, for { v := <-ch }), then after the channel is closed, the read will return the zero value but will not block. Nevertheless, if the channel is closed and has no data, reading from it immediately returns the zero value, and the loop may continue indefinitely if there is no exit condition.
Using range over a channel automatically terminates the loop when the channel is closed and all data has been read, preventing hanging.
Example of correct reading:
for v := range ch {
fmt.Println(v)
}
// The loop ends when the channel is closed
Example with ok check:
for {
v, ok := <-ch
if !ok {
break // channel is closed
}
fmt.Println(v)
}