Senior
How is data transmitted through a non-buffered channel? Does it have a buffer?
sobes.tech AI
Answer from AI
In Go, an unbuffered channel does not have an internal buffer, so data transfer through it occurs synchronously. This means that the sending goroutine blocks until another goroutine receives a value from the channel, and vice versa — the receiving goroutine blocks if there is no value in the channel.
Thus, an unbuffered channel is used for synchronization and direct data transfer between goroutines without intermediate storage.
Example:
ch := make(chan int) // unbuffered channel
// Sending goroutine
go func() {
ch <- 42 // blocks until someone reads
}()
// Receiving goroutine
val := <-ch // blocks until a value appears
fmt.Println(val) // 42
If the channel were buffered, sending could occur without blocking until the buffer is full.