【发布时间】: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。
【问题讨论】: