简体   繁体   English

如何在go中实现类似的界面?

[英]How can I implement comparable interface in go?

I've recently started studying Go and faced next issue. 我最近开始研究Go并面临下一期。 I want to implement Comparable interface. 我想实现Comparable接口。 I have next code: 我有下一个代码:

type Comparable interface {
    compare(Comparable) int
}
type T struct {
    value int
}
func (item T) compare(other T) int {
    if item.value < other.value {
        return -1
    } else if item.value == other.value {
        return 0
    }
    return 1
}
func doComparison(c1, c2 Comparable) {
    fmt.Println(c1.compare(c2))
}
func main() {
    doComparison(T{1}, T{2})
}

So I'm getting error 所以我收到了错误

cannot use T literal (type T) as type Comparable in argument to doComparison:
    T does not implement Comparable (wrong type for compare method)
        have compare(T) int
        want compare(Comparable) int

And I guess I understand the problem that T doesn't implement Comparable because compare method take as a parameter T but not Comparable . 我想我理解T没有实现Comparable的问题,因为compare方法作为参数T而不是Comparable

Maybe I missed something or didn't understand but is it possible to do such thing? 也许我错过了什么或者不理解但是可以做这样的事情吗?

Your Interface demands a method 您的界面需要一种方法

compare(Comparable) int

but you have implemented 但你已经实施了

func (item T) compare(other T) int { (other T instead of other Comparable) func (item T) compare(other T) int { (其他T代替其他可比较)

you should do something like this: 你应该做这样的事情:

func (item T) compare(other Comparable) int {
    otherT, ok := other.(T) //  getting  the instance of T via type assertion.
    if !ok{
        //handle error (other was not of type T)
    }
    if item.value < otherT.value {
        return -1
    } else if item.value == otherT.value {
        return 0
    }
    return 1
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM