4 ms·
No. There is no interface that "sortable" things implement, other than the empty interface, and no neat way to define one. Numbers and strings support <, but t
by parenthephobia 11y ago
No. There is no interface that "sortable" things implement, other than the empty interface, and no neat way to define one.
Numbers and strings support <, but there's no way to specify operators in interface, and no way to specify operators for other types anyway.
You could do
type Comparable interface {
Compare (x Comparable) int // -> -1, 0, 1
}
func Sort (x []Comparable): []Comparable {
/// ...
}
And whilst this Sort could work, how do you call it? []int isn't []Comparable, and can't be converted to one: you have to make a new array. Then, when you want an array of ints on the other end, you have to convert it back, which now involves run-time type assertions.
Even an array of something that implements Comparable isn't compatible - it can't be, because Go doesn't know Sort won't take Bar[] and put a Foo in it, if Foo and Bar both implement Comparable.
And, whilst you can define Compare for int, the other argument will be a Comparable, not a int, so you'll have to have a run-time type assertion for each comparison.
Conversely you might try
func Sort (x []interface{}, f func(interface{}, interface{})int) []interface{} {
/// ...
}
You still can't sort []int, and your comparison function can't know it's receiving int, so it will have to type-assert both arguments at each comparison.