我正在尝试创建一个方法,它将采用某种类型的结构并对它们进行操作 . 但是,我需要一个可以调用stuct实例的方法,它将返回该struct类型的对象 . 我得到一个编译时错误,因为实现接口的类型的返回类型与接口的方法返回类型不同,但那是因为接口需要返回它自己的类型的值 .
接口声明:
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 .
1 回答
*Node
未实现GraphNode
接口,因为Children()
的返回类型与接口中定义的类型不同 . 即使*Node
实现GraphNode
,也不能使用[]*Node
,其中[]GraphNode
是预期的 . 您需要声明Children()
以返回[]GraphNode
.[]GraphNode
类型的切片的元素可以是*Node
类型 .对于
GetParent()
,只需将其更改为: