第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號(hào)安全,請(qǐng)及時(shí)綁定郵箱和手機(jī)立即綁定
已解決430363個(gè)問題,去搜搜看,總會(huì)有你想問的

如何在 go 中實(shí)現(xiàn)可比較的接口?

如何在 go 中實(shí)現(xiàn)可比較的接口?

Go
慕尼黑8549860 2021-12-07 16:50:44
我最近開始學(xué)習(xí)圍棋并面臨下一個(gè)問題。我想實(shí)現(xiàn) Comparable 接口。我有下一個(gè)代碼: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})}所以我收到錯(cuò)誤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沒有實(shí)現(xiàn)的問題,Comparable因?yàn)?compare 方法作為參數(shù)T而不是Comparable.也許我錯(cuò)過了什么或不明白,但有可能做這樣的事情嗎?
查看完整描述

1 回答

?
胡說叔叔

TA貢獻(xiàn)1804條經(jīng)驗(yàn) 獲得超8個(gè)贊

你的接口需要一個(gè)方法


compare(Comparable) int


但你已經(jīng)實(shí)施


func (item T) compare(other T) int { (其他 T 而不是其他 Comparable)


你應(yīng)該做這樣的事情:


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

}


查看完整回答
反對(duì) 回復(fù) 2021-12-07
  • 1 回答
  • 0 關(guān)注
  • 689 瀏覽

添加回答

舉報(bào)

0/150
提交
取消
微信客服

購課補(bǔ)貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動(dòng)學(xué)習(xí)伙伴

公眾號(hào)

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號(hào)