【问题标题】:Why does p not satisfy the interface for c (line 106)?为什么 p 不满足 c 的接口(第 106 行)?
【发布时间】: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


【解决方案1】:

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

【讨论】:

  • Hmmn,我改了它以反映界面中的可变参数,但仍然有同样的问题:```
  • 完整的错误是什么?它应该会告诉您缺少什么。
猜你喜欢
  • 2019-09-12
  • 2017-06-14
  • 1970-01-01
  • 2021-03-16
  • 2011-04-07
  • 2013-07-08
  • 2012-06-20
  • 2020-05-12
  • 1970-01-01
相关资源
最近更新 更多