Sobes.tech
Senior

What is the difference between buffered and unbuffered channels in Go?

sobes.tech AI

Answer from AI

A buffered channel in Go has an internal fixed-size buffer that allows the sender to write multiple values into the channel without waiting for immediate receipt. This means that sending does not block until the buffer is full.

An unbuffered channel has no buffer, so the send operation blocks until another goroutine reads a value from the channel. This provides synchronization between the sender and receiver.

Example:

ch := make(chan int)        // unbuffered channel
chBuf := make(chan int, 3)  // buffered channel with a buffer size of 3

// Sending to an unbuffered channel blocks until someone reads
ch <- 1

// Sending to a buffered channel does not block until the buffer is full
chBuf <- 1
chBuf <- 2
chBuf <- 3
// Next send will block until someone reads
// chBuf <- 4

Thus, buffered channels allow more flexible synchronization and can improve performance in certain scenarios.

What is the difference between buffered and… - sobes.tech