github.com/graybobo/golang.org-package-offline-cache@v0.0.0-20200626051047-6608995c132f/x/talks/2014/go4gophers/tree-select.go (about) 1 // +build OMIT 2 3 package main 4 5 import ( 6 "fmt" 7 8 "code.google.com/p/go-tour/tree" 9 ) 10 11 func Walk(root *tree.Tree, quit chan struct{}) chan int { 12 ch := make(chan int) 13 go func() { 14 walk(root, ch, quit) 15 close(ch) 16 }() 17 return ch 18 } 19 20 func walk(t *tree.Tree, ch chan int, quit chan struct{}) { 21 if t.Left != nil { 22 walk(t.Left, ch, quit) 23 } 24 select { // HL 25 case ch <- t.Value: // HL 26 case <-quit: // HL 27 return // HL 28 } // HL 29 if t.Right != nil { 30 walk(t.Right, ch, quit) 31 } 32 } 33 34 // STOP OMIT 35 36 func Same(t1, t2 *tree.Tree) bool { 37 quit := make(chan struct{}) // HL 38 defer close(quit) // HL 39 w1, w2 := Walk(t1, quit), Walk(t2, quit) 40 for { 41 v1, ok1 := <-w1 42 v2, ok2 := <-w2 43 if v1 != v2 || ok1 != ok2 { 44 return false 45 } 46 if !ok1 { 47 return true 48 } 49 } 50 } 51 52 func main() { 53 fmt.Println(Same(tree.New(3), tree.New(3))) 54 fmt.Println(Same(tree.New(1), tree.New(2))) 55 }