封闭频道与无频道

I am working with Go channels, and I was wondering what's the difference between closing a channel and setting it to nil?

Edit:

In this example, I would like to disconnect the sender and receiver by, whether closing the channel or setting to nil. What's the best practice to do this?

Setting a channel variable to nil simply sets the variable to nil, while leaving the channel it had previously referred to initialized.

It's the same as setting any other variable to nil.

If there are other references to the channel, you could still access it. If there are not, it will be garbage collected.

Additionally, nil versus closed channels behave differently when writing or reading. From Dave Cheney's blog post, Channel Axioms, which I recommend reading in its entirety:

  • A send to a nil channel blocks forever
  • A receive from a nil channel blocks forever
  • A send to a closed channel panics
  • A receive from a closed channel returns the zero value immediately

It's in a language specification. You can receive from closed channel forever, but writing on closed channel cause runtime panic. Both operation on a nil channel blocks forever. Such a behaviour commonly used in synchronization schemes.