我正在编码golang tour execise。我可以使用for i := 0 i < 10; i++
从频道获取所有价值。但是for v := range
会致命。
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.Left != nil {
// Walk left tree
Walk(t.Left, ch)
}
ch <- t.Value
if t.Right != nil {
// Walk right tree
Walk(t.Right, ch)
}
}
func main() {
ch := make(chan int)
go Walk(tree.New(5), ch)
for i := 0; i < 10; i++ {
fmt.Println(<-ch)
}
}
输出正确。它是5,10,15 ...... 50.
当我使用for v := range ch
时。它错误了。
func main() {
ch := make(chan int)
go Walk(tree.New(5), ch)
for v := range ch {
fmt.Println(v)
}
}
输出如下。我认为这与我关闭ch是不相关的。
fatal error: all goroutines are asleep - deadlock!
goroutine 1 [chan receive]:
main.main()