Sobes.tech
Middle

What types of channels are there in Go? Tell about buffered and unbuffered.

sobes.tech AI

Answer from AI

In Go, channels can be of two main types: buffered and unbuffered.

  • Unbuffered channels are channels without an internal buffer. Sending to such a channel blocks until another goroutine reads a value from the channel, and vice versa — reading blocks until a value appears. This ensures synchronization between goroutines.

  • Buffered channels have an internal buffer of fixed size. Sending to a channel blocks only if the buffer is full, and reading blocks if the buffer is empty. This allows some level of asynchrony between sender and receiver.

Example of creation and usage:

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

// Unbuffered channel requires synchronization:
go func() {
    ch <- 42 // blocks until someone reads
}()
val := <-ch

// Buffered channel allows sending up to 3 elements without blocking:
chBuf <- 1
chBuf <- 2
chBuf <- 3
// Attempting to send a 4th element will block until some are read

valBuf := <-chBuf

Thus, the choice of channel type depends on synchronization and performance requirements.