Graph datastructure - visit method as a parameter?

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 ?

Yes it is

package main

import (

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 {

func printNode(n *Node) {

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

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.