當前位置:
首頁 > 知識 > golang查看channel緩衝區的長度

golang查看channel緩衝區的長度

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。

1

2

3

4

5

6

7

8

9

10

11

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))

}

1

2

3

4

5

6

7

8

9

10

11

12

output:

ch1 buffer len:0

ch2 buffer len:2

golang查看channel緩衝區的長度

打開今日頭條,查看更多精彩圖片
喜歡這篇文章嗎?立刻分享出去讓更多人知道吧!

本站內容充實豐富,博大精深,小編精選每日熱門資訊,隨時更新,點擊「搶先收到最新資訊」瀏覽吧!


請您繼續閱讀更多來自 程序員小新人學習 的精彩文章:

markdown常用語法
Kent Beck的test && commit|revert 敏捷協作方法

TAG:程序員小新人學習 |