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条)

报告相同问题?

悬赏问题

  • ¥100 需要跳转番茄畅听app的adb命令
  • ¥50 寻找一位有逆向游戏盾sdk 应用程序经验的技术
  • ¥15 请问有用MZmine处理 “Waters SYNAPT G2-Si QTOF质谱仪在MSE模式下采集的非靶向数据” 的分析教程吗
  • ¥50 opencv4nodejs 如何安装
  • ¥15 adb push异常 adb: error: 1409-byte write failed: Invalid argument
  • ¥15 nginx反向代理获取ip,java获取真实ip
  • ¥15 eda:门禁系统设计
  • ¥50 如何使用js去调用vscode-js-debugger的方法去调试网页
  • ¥15 376.1电表主站通信协议下发指令全被否认问题
  • ¥15 物体双站RCS和其组成阵列后的双站RCS关系验证