How can I implement a comparable interface in go?

I recently started learning Go and ran into the following problem. I want to implement the Comparable interface. I have the following code:

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}) } 

So, I get an error

 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 

And I think I understand that T does not implement Comparable , because the comparison method accepts T as a parameter, but not Comparable .

Perhaps I missed something or did not understand, but is it possible to do this?

+5
source share
1 answer

Your interface requires a method

compare(Comparable) int

but you implemented

func (item T) compare(other T) int { (another T instead of another comparable)

you should do something like this:

 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 } 
+3
source

Source: https://habr.com/ru/post/1241884/


All Articles