5 ms·
Why not make an interface called iCompare that has a single function: compare, which takes an object of type interface{}. You can then implement that single com
by jamra 13y ago
Why not make an interface called iCompare that has a single function: compare, which takes an object of type interface{}. You can then implement that single compare function, attached to your type of choice. Problem solved.
- masklinn 13y agoYou're only solving the example (painfully and incompletely as well, because now you can't sort your collection twice using different criteria, and I believe you can't sort objects you don't fully control since you can't add methods to somebody else's types — let alone a builtin, woe is you if you're attempting to sort maps). How do you handle a non-inplace sort? How do you handle implementing a treeset or a b-tree? A reference with compare-and-set semantics? Your interface won't save you from the devil of having to up- and down-cast all over the place and throw type safety into the trash.
- jamra 13y ago1. You can add methods to other people's types. 2. My solution is not incomplete. It solves the stated problem exactly. If you need to sort the objects with a different criteria, implement the interface with whichever criteria you want. It's not so difficult. Generics will not save you from having to implement some kind of comparison criteria in other languages. 3. You can add more methods to the interface for an out of place sort. 4. If you need to implement a b-tree, add the methods to whichever type you need to sort appropriately. It's not that big of a problem. You will not have to up and down cast. You only have to cast a type of interface{} to your type once and only once while you are comparing. Is your problem ideological or specific to this example?