Golang Trees — Simple and Printable

Tufin
1 min readSep 20, 2020

--

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:

  1. A key type with a String() string method
  2. A value type which is the Tree itself (recursive definition)

Source: https://github.com/Tufin/asciitree

--

--

Tufin
Tufin

Written by Tufin

From the Security Policy Company. This blog is dedicated to cloud-native topics such as Kubernetes, cloud security and micro-services.

Responses (1)