Complex sort functions

I have a slice of items each with a number of fields - something like the Facebook newsfeed. I want to sort the slice using some complex function that weighs different fields, etc etc. What is the best way to do this? Is implementing the sort.Sort interface the best option for performance and readability? The Less method could get very complex.

Yes, I think implementing sort.Sort is a good idea. It will save you the effort of implementing a sorting algorithm, plus the usual benefits in terms of composability that come by implementing an interface. The only downside is a slight additional cost due to using interfaces instead of concrete types, but it’s usually negligible.

If you think Less will get slow, consider caching its results or intermediate values (fill a new field in the structure you are comparing if found to be the zero default.) This is especially useful as Less can make you evaluate the same element more than once: it’s a big win if you can reduce everything to a single couple of values to compare.

What kind of comparison do you need to perform specifically?

3 Likes

I have used sort.Sort interface couple of time and it worked well. But I am sure that implementation will vary based on data that you want to sort.

I read this article some time back and it was good.

sorting complex items

2 Likes

I plan on calculating a rank for each item, and then sort the slice of items in descending rank. Agreed that caching results/intermediate values and then using sort.Sort is the way to go. Thank you.

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.