Junior — Middle
How should data be correctly read from a non-buffered channel?
sobes.tech AI
Answer from AI
In Go, to read data from a channel without buffering, you should use non-blocking read or read with data availability check. Channels can be buffered or unbuffered by default, but to read without buffering, unbuffered channels are usually used along with the <- operator.
Example of reading from an unbuffered channel:
ch := make(chan int) // unbuffered channel
// Sending in a separate goroutine
go func() {
ch <- 42
}()
// Reading (will wait until data appears)
value := <-ch
fmt.Println(value) // 42
To avoid blocking during read, you can use a select statement with a default case:
select {
case val := <-ch:
fmt.Println("Received", val)
default:
fmt.Println("No data")
}