我想編碼一個樹結構,其中每個節點應該有一個id和父ref/id參數。golang - 樹結構抽象
通過擴展節點結構,你應該能夠添加一些自定義參數(如標題,圖標,顏色...)。它應該被內聯,並與氧化鎂後來插入...
你可以找到下面的代碼或在這裏:https://play.golang.org/p/bbvs2iM3ri
我試圖避免添加方法的nodeExtension結構,並通過節點結構共享它。但是,CreateNode方法只獲取節點數據而不是包裝結構。
任何想法如何實現這個算法不失去自定義參數(在這種情況下的描述)?
感謝
package main
import (
"fmt"
)
type item struct {
ID string
}
type node struct {
item `bson:,inline`
Parent string
}
func (t *node) CreateNode() {
fmt.Printf("Node: %+v\n", t)
}
type nodeExtension struct {
node `bson:,inline`
Description string
}
func main() {
i := &nodeExtension{
node: node{
item: item{
ID: "1",
},
Parent: "",
},
Description: "Root node",
}
i.CreateNode()
i = &nodeExtension{
node: node{
item: item{
ID: "2",
},
Parent: "1",
},
Description: "Another node",
}
i.CreateNode()
}
// output:
// Node: &{item:{ID:1} Parent:}
// Node: &{item:{ID:2} Parent:1}
// both without description :/