当然,人们总是可以写一个for循环。但代码共享通常总是很好。那么有没有办法编写一个排序任何数组的方法?此外,表现,所以我猜测排除反思。
sort.Reverse
似乎无法奏效。以下内容无法编译:
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)
}
答案 0 :(得分:1)
[]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 <
).