p为什么不满足c的接口(第106行)?

时间:2020-04-27 20:10:32

标签: go inheritance interface tree composition


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接口上定义的接口方法,我可以使用他们可以互换吗?

我的最终目标是能够拥有一棵使用相同方法进行树遍历的节点树(不同类型的节点)。我想我可以使用不同节点类型上的接口来实现此目的。 >

1 个答案:

答案 0 :(得分:1)

PropertyNode未实现Node,因为在接口中将setChildren声明为setChildren(...*Node),但是实现具有setChildren(*Node)