dqrnsg6439 2019-07-04 04:25 采纳率: 100%
浏览 17
已采纳

游二叉树练习中的通道问题

There's an exercise about binary tree in go-tour.

I have solved this question already and some questions came up on the way.

here is the struct of tree

type Tree struct {
    Left  *Tree
    Value int
    Right *Tree
}

here's some code

//send values into channel
func Walk(t *tree.Tree, ch chan int){
    if t.Left != nil{
        Walk(t.Left, ch)
    }
    ch <- t.Value 

    if t.Right != nil{
        Walk(t.Right,ch)
    }

        //close(ch) will trigger a warning: close of a closed channel


}

//get values from channel
func main() {
    ch := make(chan int, 10)
    go Walk(tree.New(1),ch)
    //for i:=0;i<10;i++{  //this line works
    for i:= range ch{     //this line doesn't because it reads
                              //infinitely from ch
        println( i) 
    }

My question is in the main function it clearly shows that ch didn't get closed then why can't i close the channel in the Walk function?

  • 写回答

1条回答 默认 最新

  • dsd57259 2019-07-04 05:01
    关注

    Because the function is recursive, and as such, every call of Walk will reach the line to close the channel, and each of them will try to close the channel. Thus any one of them that tries to close the channel after the first one will be trying to close a closed channel.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 metadata提取的PDF元数据,如何转换为一个Excel
  • ¥15 关于arduino编程toCharArray()函数的使用
  • ¥100 vc++混合CEF采用CLR方式编译报错
  • ¥15 coze 的插件输入飞书多维表格 app_token 后一直显示错误,如何解决?
  • ¥15 vite+vue3+plyr播放本地public文件夹下视频无法加载
  • ¥15 c#逐行读取txt文本,但是每一行里面数据之间空格数量不同
  • ¥50 如何openEuler 22.03上安装配置drbd
  • ¥20 ING91680C BLE5.3 芯片怎么实现串口收发数据
  • ¥15 无线连接树莓派,无法执行update,如何解决?(相关搜索:软件下载)
  • ¥15 Windows11, backspace, enter, space键失灵