Junior — Middle
Mis juhtub, kui proovite lugeda andmeid kanalilt, mis praegu ei sisalda elemente?
sobes.tech AI
Vastus AI-lt
In Go, if you try to read from a channel that currently does not contain any elements, the behavior depends on the channel type:
- Buffered channel: if the buffer is empty, the read blocks until an element is written to the channel.
- Unbuffered channel: the read blocks until another goroutine sends a value.
Therefore, reading from an empty channel causes the current goroutine to block until data appears or the channel is closed.
Example:
ch := make(chan int)
// Reading from an empty channel will block execution
val := <-ch // blocks until someone sends a value
// To avoid blocking, you can use select with default
select {
case val := <-ch:
fmt.Println("Received", val)
default:
fmt.Println("No data in channel")
}