如何在 go 中实现可比较的接口?

我最近开始学习围棋并面临下一个问题。我想实现 Comparable 接口。我有下一个代码:


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})

}

所以我收到错误


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

我想我理解T没有实现的问题,Comparable因为 compare 方法作为参数T而不是Comparable.


也许我错过了什么或不明白,但有可能做这样的事情吗?


慕尼黑8549860
浏览 618回答 1
1回答

胡说叔叔

你的接口需要一个方法compare(Comparable) int但你已经实施func (item T) compare(other T) int { (其他 T 而不是其他 Comparable)你应该做这样的事情:func (item T) compare(other Comparable) int {&nbsp; &nbsp; otherT, ok := other.(T) //&nbsp; getting&nbsp; the instance of T via type assertion.&nbsp; &nbsp; if !ok{&nbsp; &nbsp; &nbsp; &nbsp; //handle error (other was not of type T)&nbsp; &nbsp; }&nbsp; &nbsp; if item.value < otherT.value {&nbsp; &nbsp; &nbsp; &nbsp; return -1&nbsp; &nbsp; } else if item.value == otherT.value {&nbsp; &nbsp; &nbsp; &nbsp; return 0&nbsp; &nbsp; }&nbsp; &nbsp; return 1}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go