|
|
|
|
|
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. |
|
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.