为什么这个 Golang 代码不能在多个时间之间进行选择。 channel 工作后?
请参阅下面的代码。永远不会发出“超时”消息。为什么?
package main
import (
"fmt"
"time"
)
func main() {
count := 0
for {
select {
case <-time.After(1 * time.Second):
count++
fmt.Printf("tick %d\n", count)
if count >= 5 {
fmt.Printf("ugh\n")
return
}
case <-time.After(3 * time.Second):
fmt.Printf("timeout\n")
return
}
}
}
在 Playground 上运行:http://play.golang.org/p/1gku-CWVAh
输出:
tick 1
tick 2
tick 3
tick 4
tick 5
ugh
最佳答案
因为 time.After
是一个函数,所以在每次迭代中它都会返回一个新的 channel 。如果你希望这个 channel 对于所有迭代都是相同的,你应该在循环之前保存它:
timeout := time.After(3 * time.Second)
for {
select {
//...
case <-timeout:
fmt.Printf("timeout\n")
return
}
}
Playground :http://play.golang.org/p/muWLgTxpNf .
关于time - 为什么这个 Golang 代码不能在多个时间之间进行选择。 channel 工作后?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35036653/