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 esp8266控制共阳极wrgb灯板无法关闭所有led灯
  • ¥100 python读取速度问题
  • ¥15 stm32f407使用DMA问题
  • ¥15 您好 这个API接口该怎么弄 网站搭建好了 API也有 现在就不知道该怎么填写API 不知道怎么用
  • ¥88 用uniapp写一个多端的程序,用到高德地图,用高德的JSAPI吗?
  • ¥20 关于#c++#的问题:水果店管理系统
  • ¥30 dbLinq最新版linq sqlite
  • ¥20 对D盘进行分盘之前没有将visual studio2022卸载掉,现在该如何下载回来
  • ¥15 完成虚拟机环境配置,还有安装kettle
  • ¥15 2024年全国大学生数据分析大赛A题:直播带货与电商产品的大数据分析 问题5. 请设计一份优惠券的投放策略,需要考虑优惠券的数量、优惠券的金额、投放时间段和投放商品种类等因素。求具体的python代码