Sobes.tech
Junior — Middle

What happens if you try to read data from a channel that currently contains no elements?

sobes.tech AI

Answer from AI

In Go, attempting to read from a channel that currently contains no elements depends on the channel type:

  • Buffered channel: if the buffer is empty, the read operation blocks until an element is written to the channel.
  • Unbuffered channel: the read operation blocks until another goroutine sends a value.

Thus, reading from an empty channel causes the current goroutine to block until data is available 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 the channel")
}
What happens if you try to read data from a channel… - sobes.tech