Sobes.tech
Senior

What happens if you close an already closed channel? What if you write to a nil channel?

sobes.tech AI

Answer from AI

In Go:

  • If you try to close an already closed channel, a panic occurs. This leads to the program crashing if the panic is not recovered.

  • If you try to send a value to a nil channel, the operation blocks forever (deadlock), because a nil channel is uninitialized and cannot receive values.

Example:

var ch chan int // ch == nil

// Sending to a nil channel will block the goroutine forever
// ch <- 1 // blocking

// Closing a nil channel causes a panic
// close(ch) // panic: close of nil channel

// Closing an already closed channel causes a panic
c := make(chan int)
close(c)
// close(c) // panic: close of closed channel

Therefore, before closing a channel, you need to be sure it is open, and before sending, that the channel is not nil and not closed.