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。
Example
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