Junior — Middle
What is the difference between obtaining a zero value from a closed channel and obtaining the same value from a channel you created and sent data to?
sobes.tech AI
Answer from AI
In Go, when reading from a channel, if the channel is closed and there are no more data, the read operation returns the zero value of the channel's type and false as the second return value (if using the syntax v, ok := <-ch). This signals that the channel is closed and no more data will be sent.
If you create a channel, send a zero value into it, and then read from it, the read operation will return this zero value, but ok will be true, since the channel is open and data has been received.
Summary:
- Closed channel without data: read returns zero value +
ok == false. - Open channel with zero value: read returns zero value +
ok == true.
This allows distinguishing a real zero value from a channel close signal.