Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I implement comparable interface in go?

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?

like image 571
Orest Avatar asked Jan 30 '16 12:01

Orest


People also ask

Can an interface implement comparable?

In general, if you mark an interface as Comparable to itself, any correct implementation may only use methods from this interface to perform the comparison. Otherwise this relation can't be made anti-symmetric - a necessary condition to have a consistent ordering.

What is comparable type in Golang?

Comparability by typeBasic data types are always comparable using the == and != operators: integer values, floating-point numbers, complex numbers, boolean values, string values, constant values. Array values are comparable, if they contain a comparable element type. Pointer values are comparable.

How are Go interfaces implemented?

Go Interfaces are implemented implicitly Unlike other languages like Java, you don't need to explicitly specify that a type implements an interface using something like an implements keyword. You just implement all the methods declared in the interface and you're done.

Does Golang have interface?

Go language interfaces are different from other languages. In Go language, the interface is a custom type that is used to specify a set of one or more method signatures and the interface is abstract, so you are not allowed to create an instance of the interface.


1 Answers

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
}
like image 176
Riscie Avatar answered Nov 08 '22 02:11

Riscie