golang 如何查看channel通道中未读数据的长度

版权声明:本文为翔云原创文章,未经博主允许不得转载。 https://blog.csdn.net/lanyang123456/article/details/83096127

可以通过内建函数len查看channel中元素的个数。

内建函数len的定义如下:

func len(v Type) int
The len built-in function returns the length of v, according to its type:
Array: the number of elements in v.数组中元素的个数
Pointer to array: the number of elements in *v (even if v is nil).数组中元素的个数
Slice, or map: the number of elements in v; if v is nil, len(v) is zero.其中元素的个数
String: the number of bytes in v.字节数
Channel: the number of elements queued (unread) in the channel buffer; if v is nil, len(v) is zero.通道中未读数据的个数

下面通过简单例子演示其使用方法。

package main

import "fmt"

func main() {
        c := make(chan int, 100)

        fmt.Println("1.len:", len(c))

        for i := 0; i < 34; i++ {
                c <- 0
        }
        
        fmt.Println("2.len:", len(c))

        <-c

        <-c

        fmt.Println("3.len:", len(c))
}

output:

1.len: 0
2.len: 34
3.len: 32

可以看到,定义之后,没有任何元素时,长度为0。
接着写入34个元素后,长度为34。
最后,读出两个元素后,长度变为32。

参考

https://golang.org/pkg/builtin/#len

猜你喜欢

转载自blog.csdn.net/lanyang123456/article/details/83096127
今日推荐