What is Buffered Channel in Go: Explanation and Example
buffered channel in Go is a channel with a capacity to hold a fixed number of values without blocking the sender. It allows sending multiple values before the receiver must start receiving, unlike an unbuffered channel which blocks immediately until the value is received.How It Works
Imagine a buffered channel as a mailbox with a limited number of slots. You can drop letters (values) into the mailbox up to its capacity without waiting for someone to pick them up. Once the mailbox is full, you must wait until a letter is taken out before adding more.
In Go, a buffered channel lets the sender put values into the channel buffer without blocking until the buffer is full. The receiver can then take values out at its own pace. This helps when the sender and receiver work at different speeds.
Example
This example shows a buffered channel with capacity 2. The sender sends two values without waiting. The receiver then reads them.
package main import ( "fmt" ) func main() { ch := make(chan int, 2) // Buffered channel with capacity 2 ch <- 10 // Does not block ch <- 20 // Does not block fmt.Println(<-ch) // Receives 10 fmt.Println(<-ch) // Receives 20 }
When to Use
Use buffered channels when you want to allow some flexibility between the sender and receiver speeds. For example, if the sender produces data faster than the receiver can process, a buffered channel can hold some data temporarily.
Common use cases include worker pools, pipelines, or any situation where you want to avoid blocking the sender immediately but still control memory use by limiting buffer size.
Key Points
- A buffered channel has a fixed capacity to hold values.
- Sending to a buffered channel blocks only when the buffer is full.
- Receiving blocks only when the buffer is empty.
- Buffered channels help balance work between goroutines running at different speeds.