小编Jon*_*ber的帖子

如何在Golang中使用'time.After'和'default'?

我试图理解一个简单的Golang例程代码:

package main

import (
    "fmt"
    "time"
)

func sleep(seconds int, endSignal chan<- bool) {
    time.Sleep(time.Duration(seconds) * time.Second)
    endSignal <- true
}

func main() {
    endSignal := make(chan bool, 1)
    go sleep(3, endSignal)
    var end bool

    for !end {
        select {
        case end = <-endSignal:
            fmt.Println("The end!")
        case <-time.After(5 * time.Second):
            fmt.Println("There's no more time to this. Exiting!")
            end = true
        }
    }

}
Run Code Online (Sandbox Code Playgroud)

这很好,但为什么我不能在这个"选择"块中使用简单的默认值?像这样的东西:

for !end {
    select {
    case end = <-endSignal:
        fmt.Println("The end.")
    case <-time.After(4 * time.Second): …
Run Code Online (Sandbox Code Playgroud)

go goroutine

7
推荐指数
1
解决办法
9441
查看次数

标签 统计

go ×1

goroutine ×1