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
- Q205What is a goroutine leak caused by channels? Show one and fix it.
- Q206Why is
chan struct{}preferred for signaling, and how doescloseact as a broadcast? - Q208Channels or mutexes: how do you decide?
- Q209Explain the pipeline pattern and how to cancel it properly.
- Q210What happens if you send on a closed channel inside a
selectwith adefault? - Q211Does an unbuffered channel give a happens-before guarantee? What does the memory model say about channels?