I'm making a (non-binary) tree in Golang.
In Java, I'd use something like
class Node{
List <Object> data;
}
Where data can be either a pointer to data or to a child node
In C or C++, I'd use a void*.
What type should I use in golang
I'm making a (non-binary) tree in Golang.
In Java, I'd use something like
class Node{
List <Object> data;
}
Where data can be either a pointer to data or to a child node
In C or C++, I'd use a void*.
What type should I use in golang
There are no void pointers in Go. The way to handle this is by using the empty interface interface{}
which is inherently implemented by all types. I asked a question about this awhile back which you can find here; Go equivalent of a void pointer in C
I've never tried to solve this problem in any language, would this work in Go?
go play link edit after reading the duplicate question i see you're not asking about the implementation, enjoy anyway ♥︎
package main
import (
"fmt"
)
type Node struct {
List []*Node
Data interface{}
}
func main() {
trivial := Node{}
leaf := Node{Data: 1}
tree := Node{
List: []*Node{
&leaf,
&leaf,
},
}
out(trivial)
out(leaf)
out(tree)
}
func out(x interface{}) {
fmt.Printf("%T:%+v\n", x, x)
}
// main.Node:{List:[] Data:<nil>}
// main.Node:{List:[] Data:1}
// main.Node:{List:[0xc82000e180 0xc82000e180] Data:<nil>}