Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Closed channel vs nil channel

Tags:

go

channel

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?

like image 674
elmiomar Avatar asked Apr 25 '17 16:04

elmiomar


2 Answers

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
like image 186
Flimzy Avatar answered Oct 06 '22 23:10

Flimzy


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.

like image 30
Uvelichitel Avatar answered Oct 07 '22 01:10

Uvelichitel