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。

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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM