相关疑难解决方法(0)

非初始化通道如何表现?

我有一个结构,包含一个未初始化的通道.

当我写入它时,例程会按预期阻塞,但读者永远不会被告知管道中存在某些内容.

我很惊讶没有错误,我想知道Go是做什么的.

在下面的示例中,既不显示消息pushed也不got it打印.(取消注释初始化,它将像魅力一样工作)

type MyStruct struct {
    over chan bool
}

func main() {
    nonInitialized := &MyStruct{}
    // nonInitialized.over = make(chan bool)
    go func() {
        for i := 0; i < 10; i++ {
            select {
            case <-nonInitialized.over:
                fmt.Println("got it")
            default:
                // proceed
            }
            fmt.Println("do some stuff")
            time.Sleep(10 * time.Millisecond)
        }
        panic("took too long")
    }()
    // push on the non initialized channel
    fmt.Println("pushing")
    nonInitialized.over <- true
    fmt.Println("pushed")
}
Run Code Online (Sandbox Code Playgroud)

这是游乐场https://play.golang.org/p/76zrCuoeoh

(我知道我应该初始化频道,这不是问题的目的,我想知道Go中发生的事情与未初始化的频道.)

null initialization channel go

5
推荐指数
1
解决办法
1048
查看次数

标签 统计

channel ×1

go ×1

initialization ×1

null ×1