2016-01-30 4 views
5

私は最近、勉強を始め、次の問題に直面しました。私は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 

を取得していると私は私がTComparableを実装していないという問題があるためComparableメソッドは、パラメータTとして取るの比較ではなく、理解を推測:私は次のコードを持っています。

多分私は何かを見逃した、または理解していないかもしれませんが、そのようなことをすることは可能ですか?

答えて

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

あなたはタイプアサーションの代わりにダブルダイアパッチをしたかもしれません –

+0

@Ezequiel Moreno例を投稿できますか? –

関連する問題