Junior — Middle
What is the difference between using a buffered versus unbuffered channel with a single length?
sobes.tech AI
Answer from AI
A buffered channel with length 1 in Go allows the sender to write one value into the channel without blocking if the buffer is empty. The receiver can read this value later. This provides a small degree of asynchrony between sender and receiver.
An unbuffered channel with length 0 (the default) requires the sender and receiver to be ready at the same time for the transfer — sending blocks until someone reads the value, and vice versa.
Example:
ch := make(chan int, 1) // buffered channel with length 1
ch <- 42 // does not block if the buffer is empty
ch2 := make(chan int) // unbuffered channel
// ch2 <- 42 // blocks until someone reads
Thus, a buffered channel with length 1 slightly relieves synchronization between goroutines, while an unbuffered channel requires strict data transfer synchronization.