3 ms·
Couldn't you create a common interface that you could use for the sort?
by brightball 11y ago
Couldn't you create a common interface that you could use for the sort?
- deleted 11y ago[deleted]
- xiaq 11y agoNo, the sort package requires you to define methods on the slice of what you want to sort. For instance, if you defined a struct S, you need to implement Less, Swap and Len on an alias type of []S (since you cannot implement methods on slice types).
- parenthephobia 11y agoNo. 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.
- rakoo 11y agoThe whole problem is that there is a common interface, but it's a PITA to reimplement it every time (which means copy-pasting a little less than 10 lines) when every other language gives you sorting with a single, simple, 1-line function (or even a single argument of an already existing function).