4 ms·
Another approach to this (this is used to good effect in LINQ) is to skip the `Less(i,j)` and just provide a value extractor, except golang makes that super ver
by bigdubs 10y ago
Another approach to this (this is used to good effect in LINQ) is to skip the `Less(i,j)` and just provide a value extractor, except golang makes that super verbose because you'd have to do `func(v interface{}) interface{}`
The idea would be if you have `type foo struct { ID int, Rank int }` you could provide `func(v interface{}) interface{} { return v.(foo).Rank }` and it would sort by rank.
Some level of late binding / genericity would be necessary to make this approach not as verbose.
- masklinn 10y ago> Another approach to this (this is used to good effect in LINQ) Also in Python, it's called "key functions". Of course since Go doesn't have tuples and/or user-defined ordering, it either only works for simple comparisons (e.g. by rank but not by rank and name) or you have to hand-roll some weird-ass coercion into whatever key type the language uses. > you'd have to do `func(v interface{}) interface{}` And that doesn't actually work, interface{} is not orderable. Only integers, floats and strings are "naturally" orderable.
- bigdubs 10y agoAlso time.Time (which could be thought of as two int64s) Even string ordering there is a lot left up to the implementation as far as how it is done. Do capitals come first? Does capitalization not matter? etc. For non-intrinsic types you would provide the equivalent `less` function, but in my own programming the bulk of the things I order by are intrinsic.