问题描述
我正在尝试制作一种将采用某种类型的结构并对其进行操作的方法.但是,我需要一种可以调用该构造实例的方法,该方法将返回该结构类型的对象.我收到一个编译时错误,因为实现接口的类型的返回类型与接口的方法返回类型不同,但这是因为接口需要返回其自身类型的值.
I am trying to make a method which will take structs of a certain type and do operations on them. However, I need to have a method one can call on an instance of the stuct, and it will return objects of that struct's type. I am getting a compile time error because the return type of the type which implements the interface isn't the same as the interface's method return type, but that's because the interface needs to return values of it's own type.
接口声明:
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类型.
The above method fails because it returns a pointer to a node, and the interface returns type GraphNode.
推荐答案
* Node
不实现 GraphNode
接口,因为 Children()
与界面中定义的不同.即使 * Node
实现了 GraphNode
,也不能在需要 [] GraphNode
的地方使用 [] * Node
.您需要声明 Children()
以返回 [] GraphNode
. [] GraphNode
类型的切片的元素可以是 * Node
类型.
*Node
doesn't implement the GraphNode
interface because the return type of Children()
isn't the same as that defined in the interface. Even if *Node
implements GraphNode
, you can't use []*Node
where []GraphNode
is expected. You need to declare Children()
to return []GraphNode
. The elements of a slice of type []GraphNode
can be of type *Node
.
对于 GetParent()
,只需将其更改为此:
For GetParent()
, just change it to this:
func (node *Node) GetParent() GraphNode {
return node.parent
}
这篇关于自己类型的接口方法返回值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!