Sobes.tech
Junior — Middle

What behavior is expected when attempting to read from a channel with a buffer that is currently empty?.

sobes.tech AI

Answer from AI

When attempting to read from a buffered channel in Go, if the buffer is empty, the read operation blocks until a new value is written to the channel. This behavior ensures synchronization between goroutines: the reading goroutine waits until another goroutine sends data.

Example:

ch := make(chan int, 2) // buffer of 2 elements

// Reading from an empty channel
val := <-ch // blocks until some writes a value

If the channel is closed and the buffer is empty, the read will return the zero value of the type and false, which allows detecting the end of data.

What behavior is expected when attempting to read… - sobes.tech