3 ms·
Genuinely interested: do you have a trick for making sorting a collection less copy-and-pasty?
by justinsb 13y ago
Genuinely interested: do you have a trick for making sorting a collection less copy-and-pasty?
- voidlogic 13y agoI made a bash script for this purpose, but I have actually only used it twice to be honest.
- sandGorgon 13y agocould you elaborate - what is this about ? Go newbie here.
- justinsb 13y agoTo sort an array/collection in Go, you must implement an interface with 3 methods: https://gobyexample.com/sorting-by-functions https://gobyexample.com/sorting-by-functions It's boilerplate, which generic methods would avoid. There are shortcuts for sorting common types by their natural order in Go, so you only have to write this for custom types or custom orderings.
- riffraff 13y agoI am not sure I understand why you need generics for this, doesn't C get by passing a single function pointer? Could you explain why Go needs an interface with 3 methods?
- pcwalton 13y agoType safety, and the lack of fields in interfaces. In C you have to pass the size of the elements to quicksort, but in Go you can't do that without using the unsafe module. So you need a virtual Swap() method. And because Go needs to take a single interface, and interfaces in Go can't have fields, you need a Len() method as well.
- riffraff 13y agothanks I think I understand now.