Go

What does this print? (len and cap of channels)

Question 207MediumGo 1.22 to 1.25
package main

import "fmt"

func main() {
	var n chan int
	u := make(chan int)
	b := make(chan int, 5)
	b <- 1
	b <- 2
	<-b
	close(b)
	fmt.Println(len(n), cap(n), len(u), cap(u), len(b), cap(b))
}

Output: 0 0 0 0 1 5.

A nil channel and an unbuffered channel both report 0/0. For b, two sends and one receive leave one element, and closing doesn't clear the buffer, so len is still 1.

Gotcha: len(ch) is a snapshot that is stale by the time you use it. Code like if len(ch) > 0 { v := <-ch } is a race when there are multiple consumers, and a lurking bug in general. Use len only for metrics and monitoring, never for control flow. Interviewers use this question to see whether you reach for len as a synchronization primitive.

More on Channels & select

All 38 Channels & select questions