Subscribed unsubscribe Subscribe Subscribe

Kengo's blog

Technical articles about original projects, JVM, Static Analysis and JavaScript.

Basic of Golang

Today I have finished a tour of golang, and I did an exercise at this page. The Same function is little long, but it might be acceptable.

package main

import ""
import "fmt"

// Walk walks the tree t sending all values
// from the tree to the channel ch.
func Walk(t *tree.Tree, ch chan int) {
    WalkInner(t, ch)

func WalkInner(t *tree.Tree, ch chan int) {
    if t == nil {
    ch <- t.Value
    WalkInner(t.Left, ch)
    WalkInner(t.Right, ch)

// Same determines whether the trees
// t1 and t2 contain the same values.
func Same(t1, t2 *tree.Tree) bool {
    ch1, ch2   := make(chan int), make(chan int)
    go Walk(t1, ch1)
    go Walk(t2, ch2)
    found := make(map[int]bool)
    for i := range ch1 {
        found[i] = true
    length := 0
    for i := range ch2 {
        _, ok := found[i]
        if !ok {
            return false
        length += 1
    return len(found) == length

func main() {
    ch := make(chan int)
    go Walk(tree.New(1), ch)
    for i := range ch {

    // should be true
    fmt.Println(Same(tree.New(1), tree.New(1)))
    // should be false
    fmt.Println(Same(tree.New(1), tree.New(2)))