0PricingLogin
Go Academy · Lesson

Buffered Channels

Capacity, closing channels, and range over channel

What Is a Buffered Channel?

A buffered channel has a capacity — sends do not block as long as the buffer has space. The channel acts like a queue:

package main
import "fmt"

func main() {
    ch := make(chan int, 3)  // capacity 3

    ch <- 1  // does not block — buffer has room
    ch <- 2  // does not block
    ch <- 3  // does not block
    // ch <- 4  // would block — buffer full

    fmt.Println(<-ch) // 1
    fmt.Println(<-ch) // 2
    fmt.Println(<-ch) // 3
}

Buffered Channel as Queue

Buffered channels implement a FIFO queue between goroutines:

package main
import ("fmt"; "sync")

func producer(ch chan<- int, wg *sync.WaitGroup) {
    defer wg.Done()
    for i := 1; i <= 5; i++ {
        ch <- i
        fmt.Printf("produced %d\n", i)
    }
}

func main() {
    ch := make(chan int, 2)  // buffer 2 — producer runs ahead
    var wg sync.WaitGroup
    wg.Add(1)
    go producer(ch, &wg)
    wg.Wait()
    close(ch)
    for v := range ch { fmt.Printf("consumed %d\n", v) }
}

All lessons in this course

  1. Launching Goroutines
  2. Unbuffered Channels
  3. Buffered Channels
  4. Channel Direction and Pipeline Patterns
← Back to Go Academy