为什么这个树行走函数会死锁?

Jam*_*iew 3 tree go

我正在通过Go来刷新我的记忆,并且在等效二叉树练习中绊倒了。我已经编写了一些代码来遍历看起来应该可以工作的二叉树。

package main

import (
    "golang.org/x/tour/tree"
    "fmt"
)

// Walk walks the tree t sending all values
// from the tree to the channel ch.
func Walk(t *tree.Tree, ch chan int) {
    if t == nil {
        return
    }
    ch <- t.Value
    Walk(t.Left, ch)
    Walk(t.Right, ch)
}

func main() {
    ch := make(chan int, 10)
    go Walk(tree.New(3), ch)
    for v := range ch {
        fmt.Printf("%q", v)
    }
}
Run Code Online (Sandbox Code Playgroud)

当我运行上面的代码时,我收到以下错误:

'\x1e''\x0f''\t''\x03''\x06''\f''\x15''\x12''\x1b''\x18'fatal error: all goroutines are asleep - deadlock!

goroutine 1 [chan receive]:
main.main()
    /Users/james/src/local/go-sandbox/main.go:22 +0x115

Process finished with exit code 2
Run Code Online (Sandbox Code Playgroud)

我想知道为什么它会死锁?看起来它确实在发生这种情况之前打印了一些垃圾。

ain*_*ain 5

您必须关闭通道,以便范围循环将终止:

func main() {
    ch := make(chan int, 10)
    go func() {
        Walk(tree.New(3), ch)
        close(ch)
    }()
    for v := range ch {
        fmt.Printf("%q", v)
    }
}
Run Code Online (Sandbox Code Playgroud)