type Item struct {
Y int
X int
otherProp int
}
我有一个像上面那样的结构 slice 。如何像 SQL ORDER BY X,Y
中那样先按 X 值,然后按 Y 值对 slice item []Item
进行排序?
我发现您可以从 go 1.8 开始使用 sort.Slice()
但有没有一种简单的方法可以解决这个问题,而无需多次循环 slice ?
最佳答案
按照此处的第一个示例:Package sort ,我写了以下内容...
在 Less()
函数内,我检查 X
是否相等,如果相等,则检查 Y
。
package main
import (
"fmt"
"sort"
)
type Item struct {
X int
Y int
otherProp int
}
func (i Item) String() string {
return fmt.Sprintf("X: %d, Y: %d, otherProp: %d\n", i.X, i.Y, i.otherProp)
}
// ByX implements sort.Interface for []Item based on
// the X field.
type ByX []Item
func (o ByX) Len() int { return len(o) }
func (o ByX) Swap(i, j int) { o[i], o[j] = o[j], o[i] }
func (o ByX) Less(i, j int) bool {
if o[i].X == o[j].X {
return o[i].Y < o[j].Y
} else {
return o[i].X < o[j].X
}
}
func main() {
items := []Item{
{1,2,3},
{5,2,3},
{3,2,3},
{9,2,3},
{1,1,3},
{1,0,3},
}
fmt.Println(items)
sort.Sort(ByX(items))
fmt.Println(items)
}
输出:
[X: 1, Y: 2, otherProp: 3
X: 5, Y: 2, otherProp: 3
X: 3, Y: 2, otherProp: 3
X: 9, Y: 2, otherProp: 3
X: 1, Y: 1, otherProp: 3
X: 1, Y: 0, otherProp: 3
]
[X: 1, Y: 0, otherProp: 3
X: 1, Y: 1, otherProp: 3
X: 1, Y: 2, otherProp: 3
X: 3, Y: 2, otherProp: 3
X: 5, Y: 2, otherProp: 3
X: 9, Y: 2, otherProp: 3
]
关于sorting - 如何按多个值对 go slice 进行排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46199397/