douyi1966 2016-03-25 02:59
浏览 27
已采纳

如何在Go中以相同的方式对来自多个通道的输入做出反应?

I have some concurrent code that has two different timeout intervals, one static and one dynamic. I want to react the same way to both of them. This is the gist of it:

select {
case <-time.After(staticTimeoutInterval):
    doSomething()
case <-time.After(dynamicTimeoutInterval):
    doSomething()
}

Is there any way to write doSomething() only once? It's strange that select isn't as flexible as switch in this respect.

  • 写回答

2条回答 默认 最新

  • duandan1995 2016-03-26 13:36
    关注

    In your specific case you can use something like

    timeout := min(staticTimeoutInterval, dynamicTimeoutInterval)
    
    select {
    case <-time.After(timeout):
        doSomething()
    }
    
    func min(a, b time.Duration) int {
        if a < b {
            return a
        }
        return b
    }
    

    About the seemingly inconsistent treatment of switch and select - while these statements have similar syntax, the purpose of switch is branched execution, while the purpose of select is communication.

    If I can exaggerate:

    • switch is about the part after the case expression - the case expression here is mostly a simple, side-effect free expression
    • select is about the part in the case expression - the case expression here provides you with the important communication side effect and is not trivial to implement at all

    Allowing fallthrough in select will allow you to save a couple of lines in some cases, but it will often make select statements harder to reason about. Given a similar choice in other situations, the Go creators have almost always gone with more verbose but simpler to understand.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog