Sobes.tech
Middle+

Why can't you close the channel returned by ctx.Done() using the close() function?

sobes.tech AI

Answer from AI

The channel returned by ctx.Done() in Go cannot be closed manually using close(), because this channel is managed by the context itself.

Reasons:

  • The Done() channel is created and closed within the context implementation to signal cancellation.
  • If a user tries to close this channel manually, it will cause a panic, as the channel may already be closed or closed elsewhere.
  • The context guarantees that the channel will be closed exactly once when cancellation occurs.

The correct way to work with ctx.Done() is only to read from the channel to react to cancellation, but not to attempt to close it.

Example usage:

ctx, cancel := context.WithCancel(context.Background())

// Launch a goroutine that listens for cancellation
go func() {
    <-ctx.Done()  // wait for cancellation signal
    fmt.Println("Context cancelled")
}()

// Cancel the context
cancel()

Thus, the management of the Done() channel's lifecycle is entirely on the context side, and user intervention is prohibited.

Why can't you close the channel returned by… - sobes.tech