Go
Beginner
1 min read
Unbuffered and Buffered Channels
Example
package main
import (
"fmt"
"time"
)
func producer(ch chan<- int, n int) {
for i := 0; i < n; i++ {
fmt.Printf("sending %d\n", i)
ch <- i
time.Sleep(50 * time.Millisecond)
}
close(ch) // signal that no more values will be sent
}
func consumer(ch <-chan int) {
for v := range ch { // range exits cleanly when channel is closed
fmt.Printf("received %d\n", v)
}
}
func main() {
// Unbuffered channel — synchronous handoff
unbuf := make(chan int)
go func() { unbuf <- 42 }()
v := <-unbuf
fmt.Println("unbuffered:", v)
// Buffered channel — asynchronous up to capacity
buf := make(chan int, 3)
buf <- 1
buf <- 2
buf <- 3
// All three sends succeed without a receiver (buffer has room)
fmt.Println("buffered len:", len(buf), "cap:", cap(buf))
fmt.Println(<-buf, <-buf, <-buf)
// Pipeline: producer -> consumer
pipe := make(chan int, 5)
go producer(pipe, 5)
consumer(pipe)
}