我正在尝试制作一种方法,它将接受某种类型的结构并对其进行操作。但是,我需要一个可以在结构实例上调用的方法,它将返回该结构类型的对象。我得到了一个编译时错误,因为实现接口的类型的返回类型与接口的方法返回类型不同,但这是因为接口需要返回自己类型的值。
接口声明:
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。
发布于 2017-03-06 09:21:34
*Node不实现GraphNode接口,因为Children()的返回类型与接口中定义的类型不同。即使*Node实现了GraphNode,您也不能在需要[]GraphNode的地方使用[]*Node。需要声明Children()才能返回[]GraphNode。[]GraphNode类型的切片的元素可以是*Node类型。
对于GetParent(),只需将其更改为:
func (node *Node) GetParent() GraphNode {
return node.parent
}https://stackoverflow.com/questions/42615210
复制相似问题