码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2018-10-16 19:55:19      阅读:1052      评论:0      收藏:0      [点我收藏+]

标签:channel   ack   eve   例子   uri   lan   查看   ued   长度   

可以通过内建函数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

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

标签:channel   ack   eve   例子   uri   lan   查看   ued   长度   

原文地址:https://www.cnblogs.com/lanyangsh/p/9800133.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!