如何关闭递归函数内的通道

use*_*291 3 go

我试图找到一个类似的问题,但我不能,所以我在这里问:


我正在使用close(ch)递归函数.我需要关闭通道来终止range循环.但是,由于函数是递归的,因此close运行多次,这使我:

恐慌:封闭通道关闭

如果我对close(ch)声明发表评论,我会收到:

致命错误:所有goroutines都睡着了 - 僵局!

请在下面找到我的代码:

package main

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

// Walk walks the tree t sending all values
// from the tree to the channel ch.
func Walk(t *tree.Tree, ch chan int) {
    ch<-(t.Value)
    if t.Left != nil { Walk(t.Left, ch) }
    if t.Right != nil { Walk(t.Right, ch) }
    close(ch) // => How to close a channel inside recursive function? ***
    return
}

func main() {
    ch := make(chan int)
    go Walk(tree.New(1), ch)
    for i := range ch {
        fmt.Print(i, " ")
    }
}
Run Code Online (Sandbox Code Playgroud)

Cer*_*món 11

关闭递归函数之外的通道:

func Walk(t *tree.Tree, ch chan int) {
    ch<-(t.Value)
    if t.Left != nil { Walk(t.Left, ch) }
    if t.Right != nil { Walk(t.Right, ch) }
}

func main() {
    ch := make(chan int)
    go func() {
        defer close(ch)
        Walk(tree.New(1), ch)
    }()
    for i := range ch {
        fmt.Print(i, " ")
    }
}
Run Code Online (Sandbox Code Playgroud)

  • @MichelePiccolini 答案遵循建议。发送 Goroutine 关闭通道,而不是接收 Goroutine。 (2认同)