【问题标题】:Method taking interface as a parameter inside interface接口内部以接口为参数的方法
【发布时间】:2020-05-01 13:08:59
【问题描述】:

我在 go 中声明一个接口

type comparable interface {
GetKey() float32
Compare(comparable) int

}

并通过创建这个结构来实现这个接口

type Note struct {
id       int
text     string
priority float32

}

func (note Note) GetKey() float32 {
return note.priority

}

func (note Note) Compare(note2 Note) int {
if note.priority < note2.priority {
    return -1
} else if note.priority > note2.priority {
    return 1
} else {
    return 0
}

}

但是,当我将注释对象传递给接受可比较接口作为参数的函数时,我收到“方法比较的类型错误”错误。

我是否遗漏了什么或做错了什么?请帮忙

提前致谢

【问题讨论】:

    标签: go struct interface


    【解决方案1】:

    您没有实现comparable,因为您在比较方法中使用Note 而不是comparableCompare(note2 Note)Compare(comparable) 不同。

    在Compare方法中使用comparable实现comaprable接口

    func (note Note) Compare(note2 comparable) int {
        if note.GetKey()< note2.GetKey() {
            return -1
        } else if note.GetKey()> note2.GetKey() {
            return 1
        } else {
            return 0
        }
    }
    

    【讨论】:

      【解决方案2】:

      您将comparable 声明为具有签名Compare(comparable) int 的方法。

      所以func (note Note) Compare(note2 Note) 应该是func (note Note) Compare(note2 comparable),以匹配界面。

      否则,您将无法实现相同的接口。要实现comparable,您的Compare 方法需要采用任何comparable,但您为Note 声明的方法仅采用Note,并且没有任何可比性。这是一种不同的方法。

      这是一个基于您的代码的修改后的最小示例:https://play.golang.org/p/ajH1s5gbGcQ

      【讨论】:

        猜你喜欢
        • 2021-11-09
        • 2021-02-20
        • 2017-03-05
        • 2016-12-20
        • 1970-01-01
        • 2013-10-26
        • 1970-01-01
        • 2020-07-12
        相关资源
        最近更新 更多