Sobes.tech
Middle

What will happen in a program with a goroutine that writes to a channel and uses range over the channel without closing it?

sobes.tech AI

Answer from AI

If a goroutine writes to a channel, and another goroutine performs a range over this channel without closing it, then range will wait infinitely for new values and will not terminate.

range over a channel reads values until the channel is closed. If the channel is not closed, range blocks on the read operation, waiting for new data.

As a result, the program may hang or the goroutine with range will be stuck waiting if the writer continues writing or has stopped but did not close the channel.

Example:

data := make(chan int)
go func() {
    for i := 0; i < 5; i++ {
        data <- i
    }
    // channel is not closed
}()

for v := range data {
    fmt.Println(v) // will block after 5 values
}

To allow range to finish, the channel should be closed using close(data) after writing is complete.

What will happen in a program with a goroutine that… - sobes.tech