2016-01-30 32 views
5

我最近開始學習Go並面臨下一個問題。我想實現Comparable接口。我有下面的代碼:如何在go中實現可比的界面?

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因爲比較方法需要作爲一個參數T但不Comparable

也許我錯過了一些東西或者不明白但是有可能做這樣的事情嗎?

回答

3

你的接口要求的方法

compare(Comparable) int

,但你已經實現

func (item T) compare(other T) int {(其他的T,而不是其他可比)

你應該做這樣的事情:

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 
} 
+1

太棒了!謝謝! –

+0

你可能已經做了雙重的diapatch,而不是類型斷言 –

+0

@Ezequiel Moreno你可以張貼示例嗎? –