I'm working on a project in the Go programming language where I need a tree structure and the ability to add nodes (alot of them) to the tree. Each node is a struct like the following:
type Node struct {
ip net.IP
nodes []Node
value int
}
The number of nodes each node can have is variable (between 1-4). An IP address (I'll searching for late) can be contained at the node, but most nodes will be nil for that element.
I can easily do this in other langues, but I need to find an efficient way of adding these nodes to a tree in Go.
For example, with nodes
as a slice of pointers to Node
,
package main
import (
"fmt"
"net"
)
type Node struct {
value int
ip net.IP
nodes []*Node
}
func main() {
node1 := Node{value: 1}
node2 := Node{value: 2}
node3 := Node{value: 3}
node4 := Node{value: 4}
node1.nodes = append(node1.nodes, &node2, &node3)
node2.nodes = append(node2.nodes, &node4)
node3.nodes = append(node3.nodes, &node4)
fmt.Printf("node1: %p %v
", &node1, node1)
fmt.Printf("node2: %p %v
", &node2, node2)
fmt.Printf("node3: %p %v
", &node3, node3)
fmt.Printf("node4: %p %v
", &node4, node4)
}
Output:
node1: 0xc200069100 {1 [] [0xc200069180 0xc200069200]}
node2: 0xc200069180 {2 [] [0xc200069240]}
node3: 0xc200069200 {3 [] [0xc200069240]}
node4: 0xc200069240 {4 [] []}