How can I implement comparable interface in go? [duplicate]
Asked Answered
M

1

7

I've recently started studying Go and faced next issue. I want to implement Comparable interface. I have next 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'm getting 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 guess I understand the problem that T doesn't implement Comparable because compare method take as a parameter T but not Comparable.

Maybe I missed something or didn't understand but is it possible to do such thing?

Metropolis answered 30/1, 2016 at 12:26 Comment(0)
F
7

Your Interface demands a method

compare(Comparable) int

but you have implemented

func (item T) compare(other T) int { (other T instead of other 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
}
Frogmouth answered 30/1, 2016 at 12:44 Comment(4)
You might have done double diapatch instead of type assertionFurrier
@Ezequiel Moreno Could you post example please?Metropolis
To those who downvote, what is my error here? Thank you!Frogmouth
Are you sure it's about Golang? Can you please provide a go playground example?Chantell

© 2022 - 2024 — McMap. All rights reserved.