Sobes.tech
Junior

What is a channel in Go? Tell about buffered and unbuffered channels, their differences.

sobes.tech AI

Answer from AI

In Go, a channel is a data type for transmitting values between goroutines, providing synchronization and data exchange.

Unbuffered channel — has no internal buffer. Sending to such a channel blocks until another goroutine reads the value, and vice versa. This ensures synchronous exchange.

Buffered channel — has an internal buffer of fixed size. Sending blocks only if the buffer is full, and receiving blocks if the buffer is empty. This allows some level of asynchrony.

Example:

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

Differences:

  • Unbuffered channel requires a sender and receiver to be ready at the same time.
  • Buffered channel allows sending multiple values without immediate receiving.

Channels help safely exchange data between goroutines without using mutexes.

What is a channel in Go? Tell about buffered and… - sobes.tech