翔云

Just try, don't shy. 最新文章请点击
  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

golang查看channel缓冲区的长度

Posted on 2018-11-04 10:15  翔云123456  阅读(2344)  评论(0编辑  收藏  举报

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