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

How to execute the `case` in the `select` statement only if some conditions are satisfied

我有频道:

aChan := make(chan struct{})

和超时持续时间 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
        }
    }

有没有更优雅的写法?

当持续时间小于零时,使用 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
}