3 回答
TA贡献1884条经验 获得超4个赞
另一种选择是编写函数,返回与参数签名匹配的切片上的闭包:lesssort.Slice
func ascX0DescX1(s []MySuperType) (func(int, int) bool) {
return func(i, j int) bool {
if s[i].x0 == s[j].x0 {
return s[i].x1 > s[j].x1
}
return s[i].x0 < s[j].x0
}
}
然后将其作为lessarg传递给sort.Slice:
sort.Slice(mySuperSlice, ascX0DescX1(mySuperSlice))
TA贡献1840条经验 获得超5个赞
为每个排序编写一个排序函数,并根据需要从 f1、f2 和 f3 调用:
func sortByX0AscX1Desc(s []MySuperType) {
sort.Slice(s, func(i, j int) bool {
switch {
case s[i].x0 < s[j].x0:
return true
case s[i].x0 > s[j].x0:
return false
case s[i].x1 > s[j].x1:
return true
default:
return false
}
})
}
func f1(mySuperSlice []MySuperType) {
sortByX0AscX1Desc(mySuperSlice)
// do something with the sorted list
}
func f2(mySuperSlice []MySuperType) {
sortBySomethingElse(mySuperSlice)
// do something with the sorted list
}
func f3(mySuperSlice []MySuperType) {
sortByX0AscX1Desc(mySuperSlice)
// do something with the sorted list
}
TA贡献1876条经验 获得超5个赞
您也可以省略额外的功能并在需要的地方调用排序。
type MySuperType struct {
x0, x1, x2, x3 string
}
func f1() {
fields := []MySuperType {
{ "a1", "b4", "c3", "d2" },
{ "a2", "b1", "c2", "d3" },
{ "a3", "b1", "c4", "d1" },
{ "a4", "b3", "c1", "d4" },
}
sort.SliceStable(fields, func(i, j int) bool {
return fields[i].x1 < fields[j].x1 || fields[i].x2 > fields[j].x2
})
fmt.Println("by x1, then x2: ", fields)
}
结果:通过 x1,然后 x2:[{a3 b1 c4 d1} {a2 b1 c2 d3} {a4 b3 c1 d4} {a1 b4 c3 d2}]
- 3 回答
- 0 关注
- 139 浏览
添加回答
举报