Sobes.tech
Junior

How to properly close a channel in Go?

sobes.tech AI

Answer from AI

Closing a channel means that no more data can be sent to it. Attempting to send data to a closed channel will cause a panic.

Use the close() function.

ch := make(chan int)
close(ch)

Important to know:

  • A channel should be closed once, usually by the sender.
  • Receiving data from a closed channel is possible until it is empty.
  • After the channel is drained, subsequent read operations will return the zero value of the channel's element type and false as the second boolean value, indicating the operation's success.
v, ok := <-ch // ok will be false after the channel is drained
  • Attempting to close an already closed channel will cause a panic.
  • Attempting to receive from a nil channel will block the goroutine.
  • Attempting to send to a nil channel will block the goroutine.