closure-free simple walk
This commit is contained in:
+8
-12
@@ -4,22 +4,18 @@ import (
|
|||||||
"code.google.com/p/go-tour/tree"
|
"code.google.com/p/go-tour/tree"
|
||||||
"fmt"
|
"fmt"
|
||||||
)
|
)
|
||||||
|
func walk(t *tree.Tree, ch chan int) {
|
||||||
|
if t != nil {
|
||||||
|
walk(t.Left, ch)
|
||||||
|
ch <- t.Value
|
||||||
|
walk(t.Right, ch)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// Walk walks the tree t sending all values
|
// Walk walks the tree t sending all values
|
||||||
// from the tree to the channel ch.
|
// from the tree to the channel ch.
|
||||||
func Walk(t *tree.Tree, ch chan int) {
|
func Walk(t *tree.Tree, ch chan int) {
|
||||||
// do it as a nested closure so that I can control the call to close so
|
walk(t, ch)
|
||||||
// that I can use the range-based forloop in main.main
|
|
||||||
var walk func(t *tree.Tree)
|
|
||||||
walk = func(t *tree.Tree) {
|
|
||||||
if t == nil {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
walk(t.Left)
|
|
||||||
ch <- t.Value
|
|
||||||
walk(t.Right)
|
|
||||||
}
|
|
||||||
walk(t)
|
|
||||||
close(ch)
|
close(ch)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user