I am playing around with making a Fibonacci Heap. (They are mentioned several times in an algorithms class that I'm taking, and I want to check them out.) I want the heap to use nodes of any kind, so I define a Node interface:
package node
type Node interface {
AddChild(other Node)
Less(other Node) bool
}
type NodeList []Node
func (n NodeList) AddNode(a Node) {
n = append(n, a)
}
(I use the []Node array because it has the same affect as the heap definition.) As you can see, the Node interface defines its two functions with arguments of type Node. This should mean that the functions have to accept arguments that implement the Node interface. The rest of the heap uses these nodes.
In the program that uses this heap, I make a type that implements the Node interface:
package main
import "container/list"
import node "./node"
type Element struct {
Children *list.List
Value int
}
func (e Element) AddChild(f Element) {
e.Children.PushBack(f)
}
func (e Element) Less(f Element) bool {
return e.Value < f.Value
}
func main() {
a := Element{list.New(), 1}
n := new(node.NodeList)
n.AddNode(a)
}
However, this didn't work. The compiler complains that Element doesn't have the correct function definitions for the interface.
cannot use a (type Element) as type node.Node in function argument:
Element does not implement node.Node (wrong type for AddChild method)
have AddChild(Element)
want AddChild(node.Node)
What is wrong here? Obviously Element doesn't implement the interface correctly, but I think it's because of how I defined the interface. Is there a correct way to do what I want in Go? Can interfaces refer to themselves?