【问题标题】:Interface method return value of own type自己类型的接口方法返回值
【发布时间】:2017-03-05 23:15:51
【问题描述】:

我正在尝试创建一种方法,该方法将采用某种类型的结构并对它们进行操作。但是,我需要有一个可以调用结构实例的方法,它将返回该结构类型的对象。我收到编译时错误,因为实现接口的类型的返回类型与接口的方法返回类型不同,但那是因为接口需要返回它自己类型的值。

接口声明:

type GraphNode interface {
    Children() []GraphNode
    IsGoal() bool
    GetParent() GraphNode
    SetParent(GraphNode) GraphNode
    GetDepth() float64
    Key() interface{}
}

实现该接口的类型:

type Node struct {
    contents []int
    parent   *Node
    lock     *sync.Mutex
}

func (rootNode *Node) Children() []*Node {
...
}

错误信息:

.\astar_test.go:11: cannot use testNode (type *permutation.Node) as type GraphNode in argument to testGraph.GetGoal:
*permutation.Node does not implement GraphNode (wrong type for Children method)
have Children() []*permutation.Node
want Children() []GraphNode

获取父节点的方法:

func (node *Node) GetParent() *Node {
    return node.parent
}

上面的方法失败,因为它返回一个指向节点的指针,并且接口返回类型GraphNode。

【问题讨论】:

    标签: go interface


    【解决方案1】:

    *Node 没有实现GraphNode 接口,因为Children() 的返回类型与接口中定义的不同。即使*Node 实现了GraphNode,你也不能在预期[]GraphNode 的地方使用[]*Node。您需要声明Children() 以返回[]GraphNode[]GraphNode 类型切片的元素可以是 *Node 类型。

    对于GetParent(),只需将其更改为:

    func (node *Node) GetParent() GraphNode {
        return node.parent
    }
    

    【讨论】:

    • 儿童的接收器也应该是 GraphNode 类型吗?否则,当我有一个在节点上调用的方法并返回修改后的节点时,我需要将其强制转换为 GraphNode 接口,这实际上没有意义。
    • 不,接收器应该是您编写的实际类型。那和其他接口方法定义使您的类型成为接口的实现。对于返回GraphNode 类型值的接口方法,您可以返回*Node 类型的值,因为该类型实现了接口。
    • 所以确认一下,这个问题只在返回 Nodes/GraphNodes 的切片时出现?
    • 您的方法定义必须与接口定义完全匹配(名称、参数类型、返回类型)。 GetParent 必须返回GraphNode,但在函数内,您可以返回*Node 类型的值。抱歉,如果不清楚。
    • 好的。所以在我的接口实现中,我的类型名称(节点)应该出现在原型中的唯一位置是在接收器中?其他一切都应该是接口类型?
    猜你喜欢
    • 2020-09-04
    • 2017-05-09
    • 1970-01-01
    • 2019-02-10
    • 2011-05-16
    • 1970-01-01
    • 1970-01-01
    • 2018-02-23
    • 1970-01-01
    相关资源
    最近更新 更多