I've been working in an interface to use as a hierarchical tree. The idea is to aloud the concrete implementations to call .Children()
, .Father()
and a function to auto populate the hierarchy based on a slice of {id, FatherId}
schema.
I only need three different implementations of this interface, maybe it's more convenient to do the whole thing for each struct but I'm new to Go and decided to use this example to understand interfaces.
I've come to an interface that looks something like this:
type Node interface{
Equals(nodo *Node) bool
AddChild(child *Node)
SetFather(father *Node)
Children() []Node
Father() *Node
}
So the idea is call a Populate
function:
func Populate(plainNodes []Node, HierarchichalNodes *[]Node) {}
Plain nodes would be items defining the id of his father:
{id: "Animal", father: ""}
{id: "Plant", father: ""}
{id: "Mammals", father: "Animal"}
Hierarchical nodes would be the result:
Animal
|__Mammals
Plant
The problem I'm getting is when I try to implement the interface in a concrete struct, this case "Category"
.
type Category struct{
children []Category
father Category
}
func (c Category) SetFather(node *Node) {
v, ok = node.(*Category)
c.father = v
}
Notice that in Category
I want to work with Category
father and children, not with interface Node
.
I can't do the conversion, I get :
invalid type assertion: nodo.(*Category) (non-interface type *Node on left)
Any ideas?