golang查看channel缓冲区的长度

时间:2021-06-25 01:41:51

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