golang檢視channel緩衝區的長度
阿新 • • 發佈:2018-11-04
golang提供內建函式cap用於檢視channel緩衝區長度。
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:
ch1 buffer len:0
ch2 buffer len:2