仅在满足某些条件的情况下,如何在`select`语句中执行`case`

我有一个频道:


aChan := make(chan struct{})

和超时时间var t time.Duration。如果通道关闭,或者t达到超时,我希望程序退出, 如果 t 是正的 duration。


我知道我可以使用外部 if else 循环,但这看起来非常多余:


    if t >= time.Duration(0) {

        select {

        case <-time.After(t):

            fmt.Fprintln(os.Stdout, "timeout!"))

            close(timeoutChan)

        case <-aChan:

            fmt.Fprintln(os.Stdout, "aChan is closed"))

            return

        }

    } else {

        select {

        case <-aChan:

            fmt.Fprintln(os.Stdout, "aChan is closed"))

            return

        }

    }


有没有更优雅的方式来写这个?


万千封印
浏览 87回答 1
1回答

隔江千里

nil当持续时间小于零时,使用通道进行超时。通道的超时情况nil不会执行,因为nil通道上的接收永远不会准备好。var after <-chan time.Timeif t >= 0 {&nbsp; &nbsp; after = time.After(t)}select {case <-after:&nbsp; &nbsp; fmt.Println("timeout!")&nbsp; &nbsp; close(timeoutChan)case <-aChan:&nbsp; &nbsp; fmt.Println("aChan is closed")&nbsp; &nbsp; return}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go