Buffered channels
A buffered channel holds a fixed number of values: make(chan T, n). Send parks only when the buffer is full. Receive parks only when the buffer is empty.
Detailed Explanation
ch := make(chan int, 8) is a queue of at most eight integers. A producer can run ahead by eight items. The ninth send waits. A consumer can drain the eight without the producer running at that moment. The capacity is part of the channel's identity; you cannot grow it later.
Capacity 1 is a common signal. make(chan error, 1) lets a worker send one error without blocking if the receiver is late, and without requiring the receiver to exist at send time. Capacity 0 would deadlock if the worker sends and nobody is receiving yet.
len and cap. cap(ch) is the buffer size. len(ch) is how many values are currently stored. Reading len is a snapshot, not a reservation: another goroutine can change it before you act. Do not use len == 0 as a substitute for select.
Close drains the buffer. After close, receives get buffered values first, then zeros. You can close a non-empty buffered channel; that is normal.
As a semaphore. A buffered chan struct{} of size n with n tokens (or with sends used as "slots") limits concurrency. Acquire is send or receive, depending on how you fill it. errgroup with SetLimit is clearer for "at most n goroutines."
What it costs. The buffer is allocated up front: n slots of T. A huge buffer is a huge queue and hides a stuck consumer until memory hurts. Pick n from a burst size you can name ("8 in-flight requests"), not from "so it never blocks."
Code Examples
package main
import "fmt"
func main() {
ch := make(chan int, 2)
ch <- 1
ch <- 2
fmt.Println(<-ch, <-ch)
}func oneError() error {
errc := make(chan error, 1)
go func() {
errc <- fmt.Errorf("boom")
}()
return <-errc
}func fullBlocks() {
ch := make(chan int, 1)
ch <- 1
// ch <- 2 // blocks until a receive
<-ch
}Common Gotchas
A large buffer is not a leak-proof queue
if the consumer dies, the producer still fills the buffer and then blocks.
`len(ch)` is racy as a decision
use `select` to try a non-blocking send/receive.
Closing does not discard buffered values
they are still received.