Junior — Middle
Is it possible to perform a read operation from a channel without using a buffer?
sobes.tech AI
Answer from AI
In Go, the read operation from a channel (chan) without using a buffer is only possible if the channel is buffered. If the channel is unbuffered (buffer size 0), then the read operation blocks until a value is sent to the channel.
Thus:
- For non-blocking read without a buffer, you need to use non-blocking operations with the channel (for example, via
selectwithdefault), but this does not guarantee data reception. - If the channel is unbuffered, reading always blocks until someone sends data.
Example of a buffered channel:
ch := make(chan int, 1) // buffer of 1 element
ch <- 42 // send value
val := <-ch // read without blocking
If the channel is unbuffered, read and write are synchronized directly between goroutines.