6

私は最近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

そして、compare メソッドTComparableパラメーターとして取るTComparable.

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

4

1 に答える 1

5

あなたのインターフェースはメソッドを要求しています

compare(Comparable) int

しかし、あなたは実装しました

func (item T) compare(other T) int {(他の Comparable の代わりに他の 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
}
于 2016-01-30T12:44:00.570 に答える