Closed channel vs nil channel when writing

168 views
Skip to first unread message

clement auger

unread,
Sep 1, 2019, 12:03:58 PM9/1/19
to golang-nuts
hi,

I am looking for further details and explanations about the various behaviors
associated with closed Vs nil channels.

I already read
and other publications such as

They repeat the explanation of the behaviors the programmer will have to deal with,
however they don't really explain the internal, nor the reasons of the differences
found with this example https://play.golang.org/p/4LuZ32gzWbu when closing or niling the channel

I wonder under which case it is useful to panic on write, Vs branching to a default case within a select.
Said differently what is the advantage of a panic Vs a syntax like ok := mychan <- myval; if !ok { return "not wrote" }

Yes, there are ways to handle the problem of uncertain number of senders, but there are no simple ways.
A mechanism must be designed to avoid any sender writing to a closed channel.

thanks for anyone able to provide some details.

Albert Tedja

unread,
Sep 1, 2019, 1:55:13 PM9/1/19
to golang-nuts
No such thing as a 'nil channel'. You are merely setting a variable to nil, regardless what the previous content is.

It's just that Go allows you to receive from a nil variable if that variable's type is a channel, in which case it blocks forever.

T L

unread,
Sep 2, 2019, 9:41:54 AM9/2/19
to golang-nuts

Jake Montgomery

unread,
Sep 2, 2019, 1:12:03 PM9/2/19
to golang-nuts

On Monday, September 2, 2019 at 9:41:54 AM UTC-4, T L wrote:

That is a great, and pretty detailed article. For quick reference I like https://dave.cheney.net/2014/03/19/channel-axioms .

clement auger

unread,
Sep 3, 2019, 4:08:01 AM9/3/19
to golang-nuts
The compiler will produce the same result using an uninitialized channel variable (ie nil chan);
btw, the spec admits that a "nil channel" is a valid concept, several references can be found within it.

You might as well quote the specification rather than rephrasing, it is way shorter and efficient.

"A send on a nil channel blocks forever. "

clement auger

unread,
Sep 3, 2019, 4:10:31 AM9/3/19
to golang-nuts
sorry i can t find the added value i m looking for within those two publications.

thanks for trying to help, it will be good pointers for future readers starting to learn go and reading those words.
Reply all
Reply to author
Forward
0 new messages