Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/86.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Go 通道中的元素数_Go - Fatal编程技术网

Go 通道中的元素数

Go 通道中的元素数,go,Go,使用缓冲通道,如何测量通道中有多少个元素?例如,我正在创建和发送这样一个频道: send_ch := make(chan []byte, 100) // code send_ch <- msg send_ch:=make(chan[]字节,100) //代码 发送\u ch 函数长度(v型)int len内置函数根据v的类型返回v的长度: 数组:v中的元素数 指向数组的指针:*v中的元素数(即使v为零) 切片或映射:v中的元素数;如果v为零,len(v)为零 字符串:v中的字节数 通道

使用缓冲通道,如何测量通道中有多少个元素?例如,我正在创建和发送这样一个频道:

send_ch := make(chan []byte, 100)
// code
send_ch <- msg
send_ch:=make(chan[]字节,100)
//代码
发送\u ch

函数长度(v型)int
len内置函数根据v的类型返回v的长度:

  • 数组:v中的元素数
  • 指向数组的指针:*v中的元素数(即使v为零)
  • 切片或映射:v中的元素数;如果v为零,len(v)为零
  • 字符串:v中的字节数
  • 通道:通道缓冲区中排队(未读)的元素数;如果v为零,len(v)为零

谢谢你,阿泰姆。这是对len的一种出乎意料的使用——我希望它返回通道的容量,而不是通道中元素的数量!很高兴知道,再次感谢。如果您想要容量,那么内置函数
cap
就可以了。我发现有趣的是,如果频道没有容量(
c:=make(chan int)
),您就无法获得它的长度。我还没有找到这样做的理由。是的,它的容量也返回0。我觉得奇怪,当它没有缓冲时,我无法得到它的长度。当使用goroutines时,会有点混乱。@Brettski和Berkant,如果通道没有缓冲(容量=0),那么长度将始终为零。发送方阻止,直到接收方收到该值。
package main

import "fmt"

func main() {
        c := make(chan int, 100)
        for i := 0; i < 34; i++ {
                c <- 0
        }
        fmt.Println(len(c))
}
34