|
|
|
|
|
by cmccabe
4720 days ago
|
|
That's not necessary. You can just create a type that embeds the type you're sorting, and define the Less function however you like. It's very efficient since you're just wrapping the entire slice object, not every element in the slice. package main
import "sort"
type RevIntSlice struct {
sort.IntSlice
}
func (arr RevIntSlice) Less(i, j int) bool {
return arr.IntSlice.Less(j, i)
}
func main() {
myList := RevIntSlice { sort.IntSlice {1, 2 , 3 } }
sort.Sort(myList)
for _, elem := range(myList.IntSlice) {
println(elem)
}
}
Note that if all you want to do is reverse the sort order, sort.Reverse is a better way than what I wrote here. This is just an example of the kinds of things you can do. |
|
But that's more work (and more boilerplate) than simply passing an anonymous comparator to the sort function.