我最近開始學(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ò)過了什么或不明白,但有可能做這樣的事情嗎?
如何在 go 中實(shí)現(xiàn)可比較的接口?
慕尼黑8549860
2021-12-07 16:50:44