ここから最初の例を次に示します。X
が等しく、もしそうなら、私はその後、Y
をチェックするとPackage sort、私は私がチェックLess()
関数の内部次...
を書きました。
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)
}
出力:
[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
]
その後、Yの値をXを比較します。これを行うのに問題がある場所の例を表示できますか? ( 'sort.Slice'あなたはいつもあまりにも標準' sort.Sort'でこれを行うことができ、必要とされていません。) – JimB
は、パッケージでも一般的なケースでそれを行う方法の例が含まれます。https:// golangを。 org/pkg/sort /#example__sortMultiKeysです。代わりに、2回ソートすることもできます。最初はYで、次に安定した(!)をXで実行します。 – Volker
予想される動作の例を挙げることはできますか? – tgogos