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

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

How to check if channel is full without sending anything

问题

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

select {
	case ch <- "data":
		// 已发送
	default:
		// 通道已满
}

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

英文:

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

select {
	case ch &lt;- &quot;data&quot;:
		// sent
	default:
		// channel full
}

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

答案1

得分: 2

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

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

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:

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:

确定