我一直在为一个层次树界面工作。我的想法是允许具体实现调用.Children()
, .Father()
和一个函数,可以基于{id, FatherId}
结构的切片自动填充层次结构。
我只需要这个接口的三种不同实现,也许对于每个结构体来说整个过程更方便,但我对Go语言很陌生,所以决定使用这个示例来理解接口。
我已经创建了一个类似下面这样的接口:
type Node interface{
Equals(nodo *Node) bool
AddChild(child *Node)
SetFather(father *Node)
Children() []Node
Father() *Node
}
所以,这个想法是调用一个名为
Populate
的函数:func Populate(plainNodes []Node, HierarchichalNodes *[]Node) {}
普通节点是定义其父节点id的项:
{id: "Animal", father: ""}
{id: "Plant", father: ""}
{id: "Mammals", father: "Animal"}
层级节点将是结果:
Animal
|__Mammals
Plant
我遇到的问题是,在尝试在一个具体的结构体中实现接口时,比如这个例子中的
"Category"
。type Category struct{
children []Category
father Category
}
func (c Category) SetFather(node *Node) {
v, ok = node.(*Category)
c.father = v
}
请注意,在
Category
中,我希望与Category
的父类和子类一起工作,而不是与接口Node
一起工作。我无法进行转换,会得到:
invalid type assertion: nodo.(*Category) (non-interface type *Node on left)
有什么想法吗?
*Category
的指针是一个Node
,而不是指向Node
的指针。 - Not_a_Golfer