Sobes.tech
Senior

How does a buffered channel work in Go?

sobes.tech AI

Answer from AI

A buffered channel in Go is a channel with a capacity (buffer) that allows the sender to write multiple values into the channel without blocking, until the buffer is full. The receiver can read from the channel regardless of whether the sender is blocked or not.

Example:

ch := make(chan int, 2) // channel with a buffer of 2 elements

ch <- 1 // does not block
ch <- 2 // does not block
// ch <- 3 // blocks until someone reads from the channel

fmt.Println(<-ch) // outputs 1
fmt.Println(<-ch) // outputs 2

Thus, a buffered channel helps smooth out the speed difference between sender and receiver, improving performance and reducing blocking.