[英]Golang type assertion with pointers
我一直在使用一個界面來用作分層樹。 這個想法是大聲調用.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)
有什么想法嗎?
您的參數是node *Node
,它的類型為*Node
。 Node
是一種接口類型,但*Node
不是:它是一個指向接口的指針。
不要使用指向接口的指針,它很少需要。 而是將其更改為node Node
。 還將所有其他*Node
指針更改為Node
。
此外,如果Category.SetFather()
方法打算更改標識為接收器的Category
值,則它必須是一個指針,否則您最終只會更改在SetFather()
返回后將被丟棄的副本。 所以使用像c *Category
這樣的接收器。
更進一步,如果node
參數包含包裝在接口中的*Category
,則不能直接將其分配給Category.father
因為它是非指針類型Category
。 你需要一個指針間接,例如c.father = *v
; 或將father
字段的類型更改為指針: father *Category
。
更正后的SetFather()
方法可能如下所示:
func (c *Category) SetFather(node Node) {
if v, ok := node.(*Category); ok {
c.father = *v
}
}
這應該有效:
(*nodo).(Category)
先取消引用,然后斷言。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.