Junior — Middle
Mis vahe on saada nullväärtus suletud kanalilt ja saada sama väärtus, luues kanali ise ja saates sinna andmeid?
sobes.tech AI
Vastus AI-lt
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 type and false in the second return value (if using the syntax v, ok := <-ch). This signals that the channel is closed and no more data will be available.
If, on the other hand, you create a channel, send a zero value into it, and read from it, the read operation will return that zero value, but ok will be true, because the channel is open and data has been received.
Summary:
- Closed channel without data: read returns the zero value +
ok == false. - Open channel with zero value: read returns the zero value +
ok == true.
This allows distinguishing between the actual zero value and the close signal of the channel.