How does a non initialized channel behave?

核能气质少年 提交于 2019-11-27 08:58:54

An "uninitialized" field or variable of channel type will have the zero value of all channel types which is nil. So let's examine how a nil channel or operations on it behave.

It is worth collecting the channel axioms in one post:

Reasoning for blocking in case of nil channels: if a channel value is nil, no one has a reference to it, so no one will ever be ready to receive from it (what we want to send); or send anything on it (what we would receive from it).

You can read further reasoning and more details about this in Dave Cheney: Channel Axioms.

For completeness:

  • Closing a nil channel causes a run-time panic (just like closing an already closed channel).
  • Length and capacity of a nil channel is 0; in accordance with nil slices and maps having 0 length and capacity.

Reasoning: "closed" is a state, but a nil channel cannot have a state (there is only one nil channel, and not one for "closed" and one for "not closed" channel). And there are no elements queued in a nil channel (so len = 0), and it does not have a buffer capacity (so cap = 0).

This is expected behavior. A send to a nil channel blocks forever. You can read about it in the specs here: https://golang.org/ref/spec#Send_statements

The same is also applicable for a recieve on a nil channel. (https://golang.org/ref/spec#Receive_operator)

You can also keep this link handy for reference: http://dave.cheney.net/2014/03/19/channel-axioms

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!