Of course, one can always write a for loop. But code sharing is usually always good. So is there a way to write a method that sorts any array? Also, performance, so I'm guessing that rules out reflection.
sort.Reverse
doesn't seem to work. The following will not compile:
package main
import (
"fmt"
"sort"
)
type A struct {
X int
}
func main() {
x := make([]A, 0)
x = append(x, A{1})
x = append(x, A{2})
sort.Reverse(sort.IntSlice(x))
fmt.Println(x)
}
[]A
is not an int slice, it's a slice of structs and you must implement a sort.Interface
to describe how to sort it.
Here's a working example:
package main
import (
"fmt"
"sort"
)
type A struct {
X int
}
type ByX []A
func (a ByX) Len() int { return len(a) }
func (a ByX) Swap(i, j int) { a[i], a[j] = a[j], a[i] }
func (a ByX) Less(i, j int) bool { return a[i].X < a[j].X }
func main() {
x := make([]A, 0)
x = append(x, A{1})
x = append(x, A{2})
sort.Sort(sort.Reverse(ByX(x)))
fmt.Println(x)
}
Alternatively, you can call sort.Slice
and provide it with only the Less
function:
sort.Slice(x, func(i, j int) bool { return x[i].X > x[j].X })
You should notice that the less function is different. Since we want to sort in reverse and the shorthand sort.Slice
isn't compatible with sort.Reverse
, we had to modify the less function to return the opposite (>
instead of <
).