Junior — Middle
How does a program behave when using range to read from a closed unbuffered channel?
sobes.tech AI
Answer from AI
When using range to read from a channel in Go, the loop will receive values from the channel until it is closed. If the channel is closed and all values have been read from it, range will exit the loop.
For an unbuffered channel, this works the same as for a buffered one: if the channel is closed, range does not block and exits the loop.
Example:
ch := make(chan int)
go func() {
ch <- 1
ch <- 2
close(ch)
}()
for v := range ch {
fmt.Println(v) // Will print 1 and 2, then the loop ends
}
If the channel is closed but contains no data, range will immediately end. If the channel is not closed but has no data, range will wait (block) until data appears or the channel is closed.