typestar

Buffered channels in Go

A buffer lets a sender run ahead, up to its capacity.

func buffered() (int, int, []int) {
    queue := make(chan int, 3)
    queue <- 1
    queue <- 2

    queued, capacity := len(queue), cap(queue)

    close(queue)
    var drained []int
    for value := range queue { // range stops at close
        drained = append(drained, value)
    }
    return queued, capacity, drained
}

How it works

  1. make(chan T, n) holds n values before blocking.
  2. len is what is queued, cap is the buffer size.
  3. A full buffer blocks the sender; an empty one blocks the receiver.

Keywords and builtins used here

The run, in numbers

Lines
14
Characters to type
281
Tokens
74
Three-star pace
100 tpm

At the three-star pace of 100 tokens a minute, this run takes about 44 seconds.

Type this snippet

Step 2 of 4 in Channels, step 5 of 25 in Concurrency.

← Previous Next →