elmiomar
elmiomar

Reputation: 2022

Closed channel vs nil 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?

Upvotes: 27

Views: 19276

Answers (3)

Eric
Eric

Reputation: 24954

Another critical difference is with select:

  • a closed channel, will be selected immediately, and get nil value of the channel type.
    Thus may cause the other channels in the select never get selected.
  • a nil channel, will never be selected.

Upvotes: 15

Jonathan Hall
Jonathan Hall

Reputation: 79724

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

Upvotes: 42

Uvelichitel
Uvelichitel

Reputation: 8490

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.

Upvotes: 4

Related Questions