问题描述
有人可以向我解释为什么不允许这种实施吗? 我有一个函数,该函数采用将该函数定义为参数的接口。这会引发错误。
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))
}
解决方法
签名不相同。参数类型不同:
IsLess(Node) bool // interface argument type is `Node`
IsLess(Anode) bool // method argument type is `Anode`
要解决此问题,请更改方法以使用参数类型Node
。
然后,您需要一个Value()
方法将Anode
转换为可比较的类型(例如int
):
func (a Anode) IsLess(node Node) bool { return a.Value() < node.Value() }
func (a Anode) Value() int { return int(a) }
并将其添加到您的界面定义中:
type Node interface {
IsLess(node Node) bool
Value() int // <-- add this
}