我是第一次try 频道和Goroutine.我想使用不同的Goroutine递归地遍历一棵二叉树,但只能得到要打印的第一个值,并且不明白为什么.如果我不关闭我正在使用的通道,所有的值都会打印出来,但随后会出现线程锁定问题.我也试过使用两种不同的渠道,但也不能奏效.任何帮助都将不胜感激.
package main
import "golang.org/x/tour/tree"
import "fmt"
// Walk walks the tree t sending all values
// from the tree to the channel resCh.
func Walk(t *tree.Tree, resCh chan int) {
resCh <- t.Value
if t.Left==nil && t.Right==nil {
return
}
if t.Left != nil {
go Walk(t.Left, resCh)
}
if t.Right!=nil {
go Walk(t.Right, resCh)
}
}
func main() {
resCh:= make(chan int, 10)
Walk(tree.New(1), resCh)
<-resCh
close(resCh)
for i := range resCh {
fmt.Println(i)
}
}