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

huangapple go评论85阅读模式
英文:

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
    }
}

有没有更优雅的写法?

英文:

I have a channel:

aChan := make(chan struct{})

and a timeout duration var t time.Duration. I want the program to exit either if the channel is closed, or the t timeout is reached,
if t is a positive duration.

I know I can use an outer if else loop, but this looks very redundant:

	if t &gt;= time.Duration(0) {
		select {
		case &lt;-time.After(t):
			fmt.Fprintln(os.Stdout, &quot;timeout!&quot;))
			close(timeoutChan)
		case &lt;-aChan:
			fmt.Fprintln(os.Stdout, &quot;aChan is closed&quot;))
			return
		}
	} else {
		select {
		case &lt;-aChan:
			fmt.Fprintln(os.Stdout, &quot;aChan is closed&quot;))
			return
		}
	}

Is there a more elegant way to write this?

答案1

得分: 5

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

var after <-chan time.Time
if t >= 0 {
    after = time.After(t)
}
select {
case <-after:
    fmt.Println("超时!")
    close(timeoutChan)
case <-aChan:
    fmt.Println("aChan已关闭")
    return
}
英文:

Use a nil channel for the timeout when the duration is less than zero. The timeout case with a nil channel is not executed because receive on a nil channel is never ready.

var after &lt;-chan time.Time
if t &gt;= 0 {
	after = time.After(t)
}
select {
case &lt;-after:
	fmt.Println(&quot;timeout!&quot;)
	close(timeoutChan)
case &lt;-aChan:
	fmt.Println(&quot;aChan is closed&quot;)
	return
}

huangapple
  • 本文由 发表于 2021年11月20日 01:27:39
  • 转载请务必保留本文链接:https://go.coder-hub.com/70038673.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定