在Go语言中使用select时是否有上限?

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

Is there an upper limit when using select in Go?

问题

在Go语言中使用select语句时,你可以监听多少个case呢?是否有上限,比如说10k?过多的case会带来不良影响吗?

英文:

When I use select in Go, how many cases could I listen? Is there an upper limit on it, for example, 10k? Will overmuch cases bring harmful effects?

答案1

得分: 2

不,没有实际的上限。

英文:

No, there is no practical upper limit.

答案2

得分: 1

我不相信有这样的方法。然而,select语句必须在编译时显式编写,所以除非你打算自动生成该select语句的代码,否则编写起来可能会很痛苦。如果你有一个需要在多个通道上进行选择的大型通道列表,你可以尝试使用以下代码:

for {
    for _, c := range channels {
        select {
        case val := <-c:
            // 代码...
        default:
            // 代码...
        }
    }
}
英文:

I don't believe that there is. However, selects must be written explicitly at compile-time, so unless you plan on auto-generating the code for that select statement, that sounds painful to write. If you have a big list of channels you need to select over, you should try this instead:

for {
    for _, c := range channels {
        select {
        case val := &lt;-c:
            // code...
        default:
            // code...
        }
    }
}

huangapple
  • 本文由 发表于 2014年8月20日 10:21:31
  • 转载请务必保留本文链接:https://go.coder-hub.com/25395800.html
匿名

发表评论

匿名网友

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

确定