英文:
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 >= 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
}
}
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 <-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
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论