Junior
What is the difference between buffered and unbuffered channels in Go?
sobes.tech AI
Answer from AI
Unbuffered channels require that data sending and receiving occur synchronously. The sender is blocked until the receiver is ready to accept the data, and vice versa. Their buffer size is zero.
Buffered channels have a finite buffer size. The sender is blocked only if the buffer is full, and the receiver — if the buffer is empty.
// Unbuffered channel
unbufferedChan := make(chan int)
// Buffered channel with buffer size of 5
bufferedChan := make(chan int, 5)
| Characteristic | Unbuffered channel | Buffered channel |
|---|---|---|
| Buffer size | 0 | > 0 |
| Synchronization | Synchronous interaction | Asynchronous if buffer not full/empty |
| Sender blocking | Until received by receiver | Until buffer is filled |
| Receiver blocking | Until sent by sender | Until buffer is emptied |
Unbuffered channels are used for goroutine synchronization and to ensure messages are not lost. Buffered channels are used to reduce blocking, allowing the sender to continue working while the receiver is not yet ready, or vice versa.