简体   繁体   中英

Can an anonymous go function call itself?

I'm just running through the Tour of Go, and got to the tree walker exercise. Its obvious recursion, but closing the channel is a special case after the final pop off the call stack. Anyway, I ended up implementing it thusly:

// Walk walks the tree t sending all values
// from the tree to the channel ch.
func Walk(t *tree.Tree, ch chan int) {
    var walker func(t *tree.Tree, ch chan int)
    walker = func(t *tree.Tree, ch chan int) {
        if (t.Left != nil) {
            walker(t.Left, ch)
        }
        ch <- t.Value
        if (t.Right != nil) {
            walker(t.Right, ch)
        }
    }
    walker(t, ch)
    close(ch)
}

So far my impression of go is that they prefer to avoid saying things if they can, so the declaration of var walker before the definition seems off . Perhaps I missed some detail that would allow a function to refer to itself without the declaration? It would be a little nicer if it could be:

// Walk walks the tree t sending all values
// from the tree to the channel ch.
func Walk(t *tree.Tree, ch chan int) {
    func(t *tree.Tree, ch chan int) {
        if (t.Left != nil) {
            __me__(t.Left, ch)
        }
        ch <- t.Value
        if (t.Right != nil) {
            __me__(t.Right, ch)
        }
    }(t, ch)
    close(ch)
}

This is a simple trivia question, but I'm new enough to the language that I am not finding the answer...

You cannot use a variable before it is declared, and it is not yet declared inside its initialization statement.

So yes, the declaration line is required, and no, there is no way to avoid it.

I agree with @milo-chirstiansen that it isn't possible for an anonymous func to refer to its instance in its declaration.

If you're trying to get a feel for writing idiomatic Go code, it might look a bit more like this, doing away with the anonymous func:

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

// Walker does the things, made to be called recursively
func Walker(t *tree.Tree, ch chan int) {
    if t.Left != nil {
        Walker(t.Left, ch)
    }
    ch <- t.Value
    if t.Right != nil {
        Walker(t.Right, ch)
    }
}

You might find this interesting...

Go allows some interesting things that aren't possible in other languages. This sometimes requires thinking a little differently about your code.

Frances Campoy gave a talk at GopherCon 2016 about his storied history with the concept of nil in Go. One of his examples of how nil can be used beautifully and idiomatically, involved a solution to receiving the sum for a binary tree. Below is a link starting with this piece of his talk and I'd recommend checking it out if you have the time. ref: https://youtu.be/ynoY2xz-F8s?t=16m28s

I realize you don't have control over the Tree struct in your example, but if you did, here's how your code might look: https://play.golang.com/p/iM10NQXfgw

package main

import "fmt"

// A Tree is a binary tree with integer values.
type Tree struct {
    Left  *Tree
    Value int
    Right *Tree
}

// Walk loads value into channel; caller is responsible for providing and closing chan
func (t *Tree) Walk(ch chan int) {

    // Super interesting: Go supports the calling of a func on a nil instance of a struct
    if t == nil {
        return // return nothing
    }

    t.Left.Walk(ch)  // recursively call Walk on left node
    ch <- t.Value
    t.Right.Walk(ch) // recursively call Walk on right node
}

func main() {
    // Initial value for our tree; I'm not being very idiomatic with this
    tree := &Tree{
        Left:  &Tree{Value: 2},
        Value: 1,
        Right: &Tree{Left: &Tree{Value: 4}, Value: 3},
    }

    ch := make(chan int)

    // Load values into chan in separate goroutine
    // to prevent blocking
    go func() {
        tree.Walk(ch)
        close(ch)
    }()

    // Write each val added to chan until all values
    // have been written and chan is closed
    for val := range ch {
        fmt.Println(val)
    }
}

1

2

3

4

It should be possible to avoid this, by combining runtime.Caller and reflect.Call .

But this is nothing even resembling idiomatic Go, so I don't think it applies to your practical situation, although it does address the letter of your question. :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM