Channel Len Cap Queue Depth

len on a buffered channel reports pending items and cap reports capacity; a nil channel reports zero for both and blocks forever on receive.

GoResilience

Code

gosnippet
20 lines
package main

import "fmt"

func main() {
	// len(chan) reports current queue depth, cap(chan) reports buffer capacity
	queue := make(chan string, 4)
	fmt.Println("empty:", len(queue), "cap:", cap(queue))

	queue <- "a"
	queue <- "b"
	fmt.Println("after two sends:", len(queue), "cap:", cap(queue))

	value := <-queue
	fmt.Println("received:", value, "len now:", len(queue))

	// a nil channel reports len and cap of 0: receive blocks forever
	var missing chan int
	fmt.Println("nil channel len/cap:", len(missing), cap(missing))
}

How it works

Everything happens inside the function main.

What to watch for

  • Runs on the standard library alone; nothing to install.

Using it

The signature doing the primary work is func main()

The demo output is labeled (empty:, after two sends:, received:), so the printed output reads as a trace of the operations performed.

Key statements worth quoting

queue := make(chan string, 4)
value := <-queue
queue <- "a"

Interactive Tools for This Topic

FAQ

What does Channel Len Cap Queue Depth print when run?
Running the file directly is enough — expect labeled output lines such as `empty:`, `after two sends:`, `received:`.