如何在不发送任何内容的情况下检查通道是否已满?

huangapple go评论108阅读模式
英文:

How to check if channel is full without sending anything

问题

我知道可以通过尝试发送数据来检查通道是否已满,像这样:

  1. select {
  2. case ch <- "data":
  3. // 已发送
  4. default:
  5. // 通道已满
  6. }

然而,是否有一种方法可以在不发送任何内容的情况下检查通道是否已满呢?

英文:

I know I can check if a channel is full by trying to send it something like this:

  1. select {
  2. case ch &lt;- &quot;data&quot;:
  3. // sent
  4. default:
  5. // channel full
  6. }

However, is there a way to check if a channel is full without sending anything?

答案1

得分: 2

cap(ch) 返回通道 ch 的缓冲区容量
len(ch) 返回通道 ch 中当前未处理的消息数量

因此,要检查一个通道是否已满,可以这样做:

  1. cap(ch) == len(ch)
英文:

cap(ch) returns the buffer capacity for channel ch
len(ch) returns the number of unprocessed messages currently in channel ch

So to check if a channel is full, you can do:

  1. cap(ch) == len(ch)

huangapple
  • 本文由 发表于 2021年7月25日 03:38:28
  • 转载请务必保留本文链接:https://go.coder-hub.com/68513256.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定