Hacker News new | ask | show | jobs
by TheDong 3144 days ago
So you define the Comparer interface with a Compare method. What does it look like?

If I have a struct X, then I might write it as:

    interface Comparer {
        Compare(other X)
    }
But wait, now I have to define a new interface for every type since "Compare" takes the type X in its signature so it doesn't work for type Y... If only I could define an interface that was for an unknown type T and then Compare was for that.

But that's exactly what generics are.

You know how Java has .equals? Go doesn't have an equivalent concept. Test code is neigh unreadable because there is no generic way to compare two structs of the same type. This is a similar problem.

1 comments

I am admittedly thinking of an interface from how they work in Java, so I may be making incorrect assumptions about how they work in Go, but wouldn't I have to do that anyway? In what sense can the compiler work out how I want to compare my types? If I hand it some vec3s, for instance, does it know I want them sorted by x value, or by length?

By defining an interface that assures the compiler each type has a compare(x) method, I can write a generic sort function that takes any two comparable objects and sorts them based on whatever the class of those objects decided was the ordering criteria.