A buffered channel stores a limited number of values before a receive.

buffered capacity `cap(channel)` reports the buffer size, while `len(channel)` reports how many values are waiting.

Buffered Capacity

second
buffered_capacity.go
Replay: real traced execution (multi-file project)
package main

import "fmt"

func main() {
	var second = "blue"
	queue := make(chan string, 3)

	queue <- "red"
	queue <- second

	fmt.Println("capacity=", cap(queue))
	fmt.Println("waiting=", len(queue))
	fmt.Println("first=", <-queue)
	fmt.Println("waitingAfterOne=", len(queue))
}
package main

import "fmt"

func main() {
	var second = "green"
	queue := make(chan string, 3)

	queue <- "red"
	queue <- second

	fmt.Println("capacity=", cap(queue))
	fmt.Println("waiting=", len(queue))
	fmt.Println("first=", <-queue)
	fmt.Println("waitingAfterOne=", len(queue))
}
package main

import "fmt"

func main() {
	var second = "yellow"
	queue := make(chan string, 3)

	queue <- "red"
	queue <- second

	fmt.Println("capacity=", cap(queue))
	fmt.Println("waiting=", len(queue))
	fmt.Println("first=", <-queue)
	fmt.Println("waitingAfterOne=", len(queue))
}
  1. second ← "blue", queue ← (chan string)(⟨addr A⟩)

    5func main() {6  var second→ "blue" = "blue" //@second="green", "yellow"7  queue→ (chan string)(⟨addr A⟩) := make(chan string, 3)89  queue(chan string)(⟨addr A⟩) <- "red"10  queue(chan string)(⟨addr A⟩) <- second"blue"1112  fmt.Println("capacity=", cap(queue(chan string)(⟨addr A⟩)))13  fmt.Println("waiting=", len(queue(chan string)(⟨addr A⟩)))14  fmt.Println("first=", <-queue(chan string)(⟨addr A⟩))15  fmt.Println("waitingAfterOne=", len(queue(chan string)(⟨addr A⟩)))16}
    outputcapacity= 3
    waiting= 2
    first= red
    waitingAfterOne= 1
  1. second ← "green", queue ← (chan string)(⟨addr A⟩)

    5func main() {6  var second→ "green" = "green"7  queue→ (chan string)(⟨addr A⟩) := make(chan string, 3)89  queue(chan string)(⟨addr A⟩) <- "red"10  queue(chan string)(⟨addr A⟩) <- second"green"1112  fmt.Println("capacity=", cap(queue(chan string)(⟨addr A⟩)))13  fmt.Println("waiting=", len(queue(chan string)(⟨addr A⟩)))14  fmt.Println("first=", <-queue(chan string)(⟨addr A⟩))15  fmt.Println("waitingAfterOne=", len(queue(chan string)(⟨addr A⟩)))16}
    outputcapacity= 3
    waiting= 2
    first= red
    waitingAfterOne= 1
  1. second ← "yellow", queue ← (chan string)(⟨addr A⟩)

    5func main() {6  var second→ "yellow" = "yellow"7  queue→ (chan string)(⟨addr A⟩) := make(chan string, 3)89  queue(chan string)(⟨addr A⟩) <- "red"10  queue(chan string)(⟨addr A⟩) <- second"yellow"1112  fmt.Println("capacity=", cap(queue(chan string)(⟨addr A⟩)))13  fmt.Println("waiting=", len(queue(chan string)(⟨addr A⟩)))14  fmt.Println("first=", <-queue(chan string)(⟨addr A⟩))15  fmt.Println("waitingAfterOne=", len(queue(chan string)(⟨addr A⟩)))16}
    outputcapacity= 3
    waiting= 2
    first= red
    waitingAfterOne= 1