如何仅在满足某些条件时才执行“select”语句中的“case”

Ugt*_*gty 2 concurrency go

我有一个频道:

aChan := make(chan struct{})
Run Code Online (Sandbox Code Playgroud)

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

我知道我可以使用外部 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
        }
    }

Run Code Online (Sandbox Code Playgroud)

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

Cer*_*món 5

nil当持续时间小于零时,使用超时通道。通道的超时情况nil不会执行,因为nil通道上的接收从未准备好。

var after <-chan time.Time
if t >= 0 {
    after = time.After(t)
}
select {
case <-after:
    fmt.Println("timeout!")
    close(timeoutChan)
case <-aChan:
    fmt.Println("aChan is closed")
    return
}
Run Code Online (Sandbox Code Playgroud)