Sobes.tech
Senior

What happens if you try to close an uninitialized channel?

sobes.tech AI

Answer from AI

Trying to close an uninitialized (i.e., nil) channel in Go will cause the program to panic with the message close of nil channel.

This is because only initialized channels can be closed, and a nil channel does not exist in memory and cannot be closed.

Example:

var ch chan int // ch == nil
close(ch)       // panic: close of nil channel

To avoid a panic, you should ensure that the channel is not nil before closing it.