Senior
Mida juhtub, kui loete suletud kanalilt Go-s?
sobes.tech AI
Vastus AI-lt
When reading from a closed channel in Go, the following happens:
- If there is data in the channel, it will be read as usual.
- If the channel is closed and there is no data, the read operation will return the zero value of the channel's type and
falseas the second return value (if using the two-value form).
Example:
ch := make(chan int)
close(ch)
v, ok := <-ch
fmt.Println(v, ok) // Will print: 0 false
This allows you to determine that the channel is closed and no more data will come. When reading from a closed channel without data, the goroutine does not block and immediately receives the zero value.
If you read from a closed channel without checking the second value, you may get zero data, which is important to consider in processing logic.