实现说明
Channel 的 len 与 cap 队列深度的核心是函数 main。
使用要点
- 直接运行文件,输出会带上标签,比如
empty:、after two sends:、received:——输出的每一行都能指回产生它的那次调用。
常见问题
运行「Channel 的 len 与 cap 队列深度」会打印什么?
文件本身就是完整程序,直接运行——输出行带有 empty:、after two sends:、received: 这类标签。
核心语句
queue := make(chan string, 4)
value := <-queue
queue <- "a"
代码示例
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))
}