Posted
技术标签:
【中文标题】带有指针的 Golang 类型断言【英文标题】:Golang type assertion with pointers 【发布时间】:2017-02-13 20:39:15 【问题描述】:.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
CategoryCategoryNode
我无法进行转换,我得到了:
invalid type assertion: nodo.(*Category) (non-interface type *Node on left)
有什么想法吗?
【问题讨论】:
*CategoryNodeNode
【参考方案1】:
node *Node*NodeNode*Node
node Node*NodeNode
Category.SetFather()CategorySetFather()c *Category
node*CategoryCategory.fatherCategoryc.father = *vfatherfather *Category
SetFather()
func (c *Category) SetFather(node Node)
if v, ok := node.(*Category); ok
c.father = *v
【讨论】:
如何使 SetFather 成为(指针?)接口的方法?NodeSetFather()Nodefunc (c *Category) SetFather(node Node)SetFather()*CategoryNode*CategroyNode*CategoryNode
经常使用指向接口的指针。没有它们,Go 的 http-package 将无法工作。
只是不要在函数头中写 node *Node (但如果你想使用指针,请将指针保留在其他地方)。【参考方案2】:
这应该可行:
(*nodo).(Category)
先去引用,后断言。
【讨论】:
以上是关于带有指针的 Golang 类型断言的主要内容,如果未能解决你的问题,请参考以下文章