golang官方练习:查找二叉树
$ cat>exercise_equivalent_binary_trees.go<<EOF
package main
import "fmt"
import "golang.org/x/tour/tree"
// Walk walks the tree t sending all values
// from the tree to the channel ch.
func Walk(t *tree.Tree, ch chan int) {
if t == nil {
return
}
Walk(t.Left, ch)
ch <- t.Value
Walk(t.Right, ch)
}
// Same determines whether the trees
// t1 and t2 contain the same values.
func Same(t1, t2 *tree.Tree) bool {
ch1 := make(chan int, 10)
ch2 := make(chan int, 10)
go Walk(t1, ch1)
go Walk(t2, ch2)
var v1, v2 int
for i := 0; i < 10; i++ {
v1 = <-ch1
v2 = <-ch2
if v1 != v2 {
return false
}
}
return true
}
func main() {
fmt.Println(Same(tree.New(1), tree.New(1)))
fmt.Println(Same(tree.New(1), tree.New(2)))
}
EOF
#NOTE: 提示,缺少 go.mod 文件
[root@sltvb7v2wy3 jia_concurrency]# gor exercise_equivalent_binary_trees.go
exercise_equivalent_binary_trees.go:4:8: no required module provides package golang.org/x/tour/tree: go.mod file not found in current directory or any parent directory; see 'go help modules'
#NOTE: 生成 go.mod, go.sum
[root@sltvb7v2wy3 jia_concurrency]# go mod init example.com/exercise_equivalent_binary_trees.go
go: creating new go.mod: module example.com/exercise_equivalent_binary_trees.go
go: to add module requirements and sums:
go mod tidy
[root@sltvb7v2wy3 jia_concurrency]# cat go.mod
module example.com/exercise_equivalent_binary_trees.go
go 1.19
[root@sltvb7v2wy3 jia_concurrency]# go mod tidy
go: finding module for package golang.org/x/tour/tree
go: found golang.org/x/tour/tree in golang.org/x/tour v0.1.0
[root@sltvb7v2wy3 jia_concurrency]# cat go.mod
module example.com/exercise_equivalent_binary_trees.go
go 1.19
require golang.org/x/tour v0.1.0
[root@sltvb7v2wy3 jia_concurrency]#
[root@sltvb7v2wy3 jia_concurrency]#
[root@sltvb7v2wy3 jia_concurrency]# cat go.sum
golang.org/x/tour v0.1.0 h1:OWzbINRoGf1wwBhKdFDpYwM88NM0d1SL/Nj6PagS6YE=
golang.org/x/tour v0.1.0/go.mod h1:DUZC6G8mR1AXgXy73r8qt/G5RsefKIlSj6jBMc8b9Wc=
[root@sltvb7v2wy3 jia_concurrency]# gor exercise_equivalent_binary_trees.go
true
false