Sobes.tech
Senior

What channels are available in Go? How does a buffered channel differ from an unbuffered one?

sobes.tech AI

Answer from AI

In Go, channels are used for data transfer between goroutines and synchronization.

There are two main types of channels:

  1. Unbuffered channel — has no internal buffer. The sending goroutine blocks until the receiving goroutine reads the value. Similarly, the receiving goroutine blocks if the channel is empty.

  2. Buffered channel — has an internal buffer of fixed size. The sending goroutine blocks only if the buffer is full, and the receiving goroutine blocks if the buffer is empty.

An internally buffered channel stores values in a circular buffer, allowing multiple values to be sent without immediate reading, increasing asynchrony and throughput.

Example of creating channels:

ch1 := make(chan int)       // unbuffered
ch2 := make(chan int, 5)    // buffered with size 5

Buffered channels are useful when smoothing out load spikes or avoiding blocking during short delays between sending and receiving.

What channels are available in Go? How does a… - sobes.tech