5 ms·
http://golang.org/pkg/sort/#Sort http://golang.org/pkg/sort/#Sort So, something like that? Interfaces, man. They're better than you think.
by NateDad 12y ago
http://golang.org/pkg/sort/#Sort http://golang.org/pkg/sort/#Sort
So, something like that?
Interfaces, man. They're better than you think.
- noelwelsh 12y agoAnd in a wonderfully ironic twist, you've completely missed the parent's general point while addressing the specific issue they used to illustrate it. Data structures are the obvious use for generics. There are also things like monads and so forth, used for example in Rust's result type.
- coldtea 12y agoYeah, fuck this type safety and performance thing...
- NateDad 12y agoIt's type safe and there's little performance hit. Please note that the "Interface" there is not "interface{}" ... it is a somewhat unfortunately named interface: http://golang.org/pkg/sort/#Interface http://golang.org/pkg/sort/#Interface The Go authors were following a practice that seemed like a good idea at first, and they've now admitted was probably a mistake... i.e. if your package is mostly about a single interface, name the package something informative, and call the interface type "Interface". This works relatively well from calling code, since it'll be referenced as "sort.Interface", but it makes the documentation for the type potentially confusing.
- coldtea 12y agoOK, thought you meant the interface{} thing people go for, since Go doesn't have generics. This Sort.Interface thing is indeed safe and performant. On the other hand its not a solution to the problem we're discussing (that, to quote the parent, due to lack of generics "it is tedious to write library code in the language"). You still have to implement it all the time for all types despite having identical implementations. So this doesn't show how it's not tedious. It just shows that it can be done in some way, which nobody doubted.
- pcwalton 12y agoIt's not very friendly to the optimizer though. In order to achieve the same performance as a templated generic version by eliminating vtable dispatch, the optimizer needs to (1) convert the recursive sort function to a loop; (2) inline the sort function; (3) promote the interface to the stack via escape analysis; (4) SROA the interface; (5) constant-propagate the SROA'd functions to their use sites; (6) inline the now-constant functions. You need a pretty powerful optimization framework with a well-tuned pipeline like GCC or LLVM in order to do all of that.
- gnuvince 12y agoSorting is not the best example of Go's simplicity: it involves creating a new type, implementing methods on that type to satisfy an interface and casting the original collection to the new type (I count four concepts). Contrast with a language like OCaml or even C where you pass a function (one concept).