Go 为什么p不满足c的接口(第106行)?
这行->Go 为什么p不满足c的接口(第106行)?,go,inheritance,interface,tree,composition,Go,Inheritance,Interface,Tree,Composition,这行->c.setChildren(p)在编译时失败,说我不能将PropertyNode用作*节点,我的印象是PropertyNode具有节点接口上定义的接口方法,我可以互换使用它们 我的最终目标是能够有一个节点树(不同类型的节点),它们使用相同的方法进行树遍历。。我想我可以在不同的节点类型上使用接口来实现这一点。PropertyNode没有实现node,因为setChildren在接口中声明为setChildren(…*node),但是实现有setChildren(*node).Hmmn,我更
c.setChildren(p)
在编译时失败,说我不能将PropertyNode用作*节点,我的印象是PropertyNode具有节点接口上定义的接口方法,我可以互换使用它们
我的最终目标是能够有一个节点树(不同类型的节点),它们使用相同的方法进行树遍历。。我想我可以在不同的节点类型上使用接口来实现这一点。
PropertyNode
没有实现node
,因为setChildren
在接口中声明为setChildren(…*node)
,但是实现有setChildren(*node)
.Hmmn,我更改了它以反映界面中的变量,但仍然存在相同的问题:``完全错误是什么?它应该告诉您缺少什么。方法签名不匹配。你也在很多地方使用*节点
,而指向接口的指针几乎从来都不是你想要的。没错,我最终匹配了函数签名,然后不得不删除所有指针。
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)
}
}