登录
首页 >  Golang >  Go问答

为何接口 c 在第 106 行上被 p 拒绝了?

来源:stackoverflow

时间:2024-02-24 11:36:15 216浏览 收藏

Golang小白一枚,正在不断学习积累知识,现将学习到的知识记录一下,也是将我的所得分享给大家!而今天这篇文章《为何接口 c 在第 106 行上被 p 拒绝了?》带大家来了解一下##content_title##,希望对大家的知识积累有所帮助,从而弥补自己的不足,助力实战开发!


问题内容

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

我的最终目标是能够拥有一个使用相同方法进行树遍历的节点树(不同类型的节点)。我认为我可以使用不同节点类型上的接口来完成此任务。


解决方案


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

以上就是本文的全部内容了,是否有顺利帮助你解决问题?若是能给你带来学习上的帮助,请大家多多支持golang学习网!更多关于Golang的相关知识,也可关注golang学习网公众号。

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>