Skip to content
Junior–Senior6,356 viewsAsked at 27 companies

What are unbuffered channels used for? Why can't a channel with a large buffer always be used?

Practice

AI answer

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.