How does a non initialized channel behave?

后端 未结 2 1243
别跟我提以往
别跟我提以往 2020-11-27 06:52

I have a struct that holds a channel that is not initialized.

When I write into it, the routine is blocking as expected but the reader is never notified that somethi

2条回答
  •  鱼传尺愫
    2020-11-27 07:47

    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:

    • a send on a nil channel blocks forever (Spec: Send statements)
    • a receive from a nil channel blocks forever (Spec: Receive operator)
    • a send to a closed channel panics (Spec: Send statements)
    • a receive from a closed channel returns the zero value immediately (Spec: Receive operator)

    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).

提交回复
热议问题