接口方法返回自己类型的值



我正在尝试制作一种方法,该方法将采用某种类型的结构并在其上进行操作。但是,我需要有一种方法可以在柱子的实例上调用,它将返回该结构类型的对象。我遇到了编译时间错误,因为实现接口的类型的返回类型与接口的方法返回类型不同,但这是因为接口需要返回其自己类型的值。

接口声明:

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。

*Node不能实现GraphNode接口,因为Children()的返回类型与接口中定义的返回类型不同。即使*Node实现GraphNode,也无法在预期[]GraphNode的位置使用[]*Node。您需要声明Children()才能返回[]GraphNode[]GraphNode类型的元素可以是*Node类型。

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

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

最新更新