By Reuven Harrison
Creating a tree in go is easy with the built-in map type:
type Tree map[string]Tree
If you want a richer node type you can use a struct as the key:
type TreeNode struct {
Name string
Data int
}type Tree map[TreeNode]Tree
And for complex nodes (go requires map keys to be comparable), you can always use a pointer:
type Tree map[*regexp.Regexp]Tree
Printing the tree may be useful for debugging and reporting so I created a small go module to print an ASCII tree from any map-based tree in go. The output looks like this:
├ root1
│ ├ sibling1
│ └ sibling2
│ ├ sibling1
│ └ sibling2
└ root2
├ sibling1
└ sibling2
And you use it like this:
type Tree map[string]Treetree := Tree{
"root": Tree{"sibling": nil},
}tree.Fprint(os.Stdout, true, "")
Which outputs:
root
└ sibling
The code works for any map-based tree that has:
- A key type with a String() string method
- A value type which is the Tree itself (recursive definition)