Junior — Middle
Explain the principle of operation of a non-buffered data transfer channel.
sobes.tech AI
Answer from AI
A unbuffered channel in Go is a channel with a capacity of 0, meaning it does not store values internally. Sending to such a channel blocks until another goroutine receives the value, and vice versa — receiving blocks until a sender appears.
This ensures synchronization between goroutines: the sender and receiver must meet simultaneously to transfer data.
Example:
ch := make(chan int) // unbuffered channel
// Sending
go func() {
ch <- 42 // blocks until someone reads
}()
// Receiving
val := <-ch // blocks until someone sends
fmt.Println(val) // will print 42
Such a channel is useful for synchronization and data transfer "on demand" without buffering.