I am implementing a tree. It is defined by the struct “Graph” and the struct “Node”.
Now I want to implement the visit method. Namely I want to write an algorithm that visits every node (very simple) and for each node calls a visitNode() method. This visitNode method will be called for each node.
Now I this visitMethod to be given as a parameter to my visit function. Visit function iterates through each node n, and calls visitMethod(n).
func (g * Graph) visit( Visit func(*Node)) <- is this the way my visit method is supposed to get another method as a parameter ?
package main
import (
"fmt"
)
type Node struct {
value interface{}
}
// A very flat graph :)
type Graph struct {
children []*Node
}
func (g * Graph) Visit(visit func(*Node)) {
for _, n := range g.children {
visit(n)
}
}
func printNode(n *Node) {
fmt.Println(n.value)
}
func main() {
g := Graph{}
g.children = []*Node{&Node{value: "I'm a node"}, &Node{value: "I'm a another node"}}
// Anonymous function
g.Visit(func(n *Node) { fmt.Println(n.value) })
// Named function
g.Visit(printNode)
}