Reputation: 29
Can someone explain to me why this kind of implementation is not allowed in go? I have a function that takes the interface the function is defined in as an argument. This throws an error.
package main
import (
"fmt"
)
type Anode int
func (a Anode) IsLess(node Anode) bool { return a < node }
type Node interface {
IsLess(node Node) bool
}
func test(a, b Node) bool {
return a.IsLess(b)
}
func main() {
a := Anode(1)
b := Anode(2)
fmt.Println(test(a, b))
}
Upvotes: 0
Views: 1847
Reputation: 22147
The signatures are not the same. The argument types are different:
IsLess(Node) bool // interface argument type is `Node`
IsLess(Anode) bool // method argument type is `Anode`
To fix this - change your method to use argument type Node
.
You'll then need a Value()
method to convert Anode
into a comparable type (e.g. int
):
func (a Anode) IsLess(node Node) bool { return a.Value() < node.Value() }
func (a Anode) Value() int { return int(a) }
And add this to your interface definition:
type Node interface {
IsLess(node Node) bool
Value() int // <-- add this
}
Playground: https://play.golang.org/p/TmGcBpUQzGs
Upvotes: 6