golang提供内建函数cap用于查看channel缓冲区长度。golang
cap的定义以下:函数
func cap(v Type) int The cap built-in function returns the capacity of v, according to its type: - Array: the number of elements in v (same as len(v)).等同于len - Pointer to array: the number of elements in *v (same as len(v)).等同于len - Slice: the maximum length the slice can reach when resliced; if v is nil, cap(v) is zero.对于slice,表示在不从新分配空间的状况下,能够达到的切片的最大长度。若是切片是nil, 则长度为0. - Channel: the channel buffer capacity, in units of elements;表示缓冲区的长度。 if v is nil, cap(v) is zero. 若是通道是nil,则缓冲区长度为0。
package main import ("fmt") func main(){ ch1 := make(chan int) ch2 := make(chan int, 2)//缓冲区长度为2 fmt.Println("ch1 buffer len:", cap(ch1)) fmt.Println("ch2 buffer len:", cap(ch2)) }
output:ui
ch1 buffer len:0
ch2 buffer len:2code