von hier das erste Beispiel Folgende: Package sort, schrieb ich folgendes ...
Innerhalb der Less()
Funktion ich überprüfen, ob X
gleich und wenn ja sind, ich Y
dann überprüfen.
playground demo
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)
}
Ausgang:
[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
]
Vergleichen Sie die X- und Y-Werte. Können Sie ein Beispiel zeigen, wo Sie Probleme haben? ('sort.Slice' ist nicht erforderlich, Sie können dies auch immer mit dem Standard' sort.Sort' machen.) – JimB
Das Paket enthält sogar ein Beispiel, wie es im allgemeinen Fall gemacht wird: https: // golang. org/pkg/sort/# beispiel__sortMultiKeys. Alternativ können Sie zweimal sortieren: Zuerst auf Y und dann stabil (!) Auf X. – Volker
Können Sie ein Beispiel für das erwartete Verhalten geben? – tgogos