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?
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.