Sobes.tech
Middle

If a writer (a goroutine that fills a channel with values) decides to close the channel, what will happen? How should the reader react to this, what problems might arise, and how can they be addressed?

sobes.tech AI

Answer from AI

When a writer (goroutine) closes a channel, it signals to readers that there will be no more new values.

What happens:

  • When reading from a closed channel, if there are still values in the channel, they will be received.
  • After all values are read, further reads from the closed channel return the zero value of the channel type and a flag ok == false.

Readers should check the second parameter when reading from a channel:

v, ok := <-ch
if !ok {
    // Channel is closed, can stop reading
}

Problems and recommendations:

  • Only the writer should close the channel to avoid panics.
  • If a reader tries to write to a closed channel — it will panic.
  • If there are multiple writers, coordination is needed to avoid closing the channel twice.

Thus, the reader should correctly handle channel closure by checking ok and stopping reading, and the writer should close the channel carefully when no more values will be sent.

If a writer (a goroutine that fills a channel with… - sobes.tech