私は最近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 メソッドT
はComparable
パラメーターとして取るT
がComparable
.
多分私は何かを逃したか理解できませんでしたが、そのようなことは可能ですか?