Sobes.tech
Senior

Who should close the output channel out — the merge function or main?

sobes.tech AI

Answer from AI

The output channel out should be closed by the creator and responsible for its lifecycle. In the merge pattern, the function receives multiple input channels and merges them into a single output channel out.

Since merge creates the out channel and writes data to it, it should be the one to close it once all input channels are closed and data has been sent.

If main creates the out channel and passes it to merge, then main should close the channel. But in the classic version, merge creates and closes the channel itself.

In summary:

  • If merge creates the out channel — it also closes it.
  • If the channel is created externally and passed to merge — the owner of the channel (e.g., main) closes it.

This prevents panic from closing the channel multiple times by different goroutines and ensures proper termination of data transfer.