【发布时间】:2020-08-11 12:34:50
【问题描述】:
import "fmt"
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
type NodeType uint
const (
COMMAND NodeType = iota
PROPERTY
)
type Node interface {
setChildren(...*Node)
getChildren() []*Node
setParent(*Node)
getParent() *Node
getFlavor() NodeType
getValue() string
}
// Command Node
type CommandNode struct {
self *Node
parent *Node
children []*Node
command string
level int
partial, complete bool
}
func (cn *CommandNode) setChildren(child ...*Node) {
for _,v := range child {
cn.children = append(cn.children,v)
}
}
func (cn *CommandNode) getChildren() []*Node {
return cn.children
}
func (cn *CommandNode) setParent(parent *Node) {
cn.parent = parent
}
func (cn *CommandNode) getParent() *Node {
return cn.parent
}
func (cn *CommandNode) getFlavor() NodeType {
return COMMAND
}
func (cn *CommandNode) getValue() string {
return cn.command
}
// Property Node
type PropertyNode struct {
self *Node
parent *Node
children []*Node
property string
level int
partial, complete bool
}
func (pn *PropertyNode) setChildren(child ...*Node) {
for _,v := range child {
pn.children = append(pn.children,v)
}
}
func (pn *PropertyNode) getChildren() []*Node {
return pn.children
}
func (pn *PropertyNode) setParent(parent *Node) {
pn.parent = parent
}
func (pn *PropertyNode) getParent() *Node {
return pn.parent
}
func (pn *PropertyNode) getFlavor() NodeType {
return PROPERTY
}
func (pn *PropertyNode) getValue() string {
return pn.property
}
func main() {
c := CommandNode{
command: "command",
}
p := PropertyNode{
property: "data 1, data 2, data 3",
}
c.setChildren(&p)
x := c.getChildren()
for k,v := range x {
fmt.Printf("x[%d] is %v\n",k,v)
}
}
这一行 -> c.setChildren(p) 编译失败,说我不能将 PropertyNode 用作 *Node,我的印象是 PropertyNode 具有 Node 接口上定义的接口方法,我可以互换使用它们?
我的最终目标是能够拥有一棵使用相同方法进行树遍历的节点树(不同类型的节点)。我想我可以在不同节点类型上使用接口来实现这一点。
【问题讨论】:
-
方法签名不匹配。你还在很多地方使用
*Node,而指向接口的指针几乎从来都不是你想要的。 -
你是对的,我最终匹配了函数签名然后不得不删除所有指针。
标签: go inheritance interface tree composition