Sobes.tech
Middle

What is the difference between a buffered and unbuffered channel in Go?

sobes.tech AI

Answer from AI

A buffered channel in Go has an internal buffer of a specified size, which allows the sender to write multiple values without blocking until the buffer is full. An unbuffered channel has no buffer, so the sender blocks until the receiver reads the value.

Example:

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

ch <- 1 // does not block, buffer is empty
ch <- 2 // does not block, buffer is not yet full
// ch <- 3 // blocks until someone reads from the channel

val := <-ch // reading from the channel

In an unbuffered channel:

ch := make(chan int) // unbuffered channel

// ch <- 1 // blocks until there is a receiver

go func() {
    val := <-ch
    fmt.Println(val)
}()

ch <- 1 // now the send does not block, as there is a receiver

Thus, buffered channels allow more flexible data exchange between goroutines without immediate synchronization.

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