问题
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.
Interface declaration:
type GraphNode interface {
Children() []GraphNode
IsGoal() bool
GetParent() GraphNode
SetParent(GraphNode) GraphNode
GetDepth() float64
Key() interface{}
}
Type which implements that interface:
type Node struct {
contents []int
parent *Node
lock *sync.Mutex
}
func (rootNode *Node) Children() []*Node {
...
}
Error Message:
.\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
Method to get parent:
func (node *Node) GetParent() *Node {
return node.parent
}
The above method fails because it returns a pointer to a node, and the interface returns type GraphNode.
回答1:
*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
.
For GetParent()
, just change it to this:
func (node *Node) GetParent() GraphNode {
return node.parent
}
来源:https://stackoverflow.com/questions/42615210/interface-method-return-value-of-own-type