在 GoLang 中排序对

Sort pair in GoLang

我知道如何对 key/value 数据类型进行排序:

map[1:a 2:c 0:b]

使用 sort Go 语言包。我怎样才能像下面这样对 Pair 进行排序:

[{c 2} {a 1} {b 0}]

我希望整个对根据键或值排序?最终结果:

[{a 1} {b 0} {c 2}]

这是根据键排序的。以下按数值排序:

[{b 0} {a 1} {c 2}]

您可以为自定义类型实施 LenSwapLess。这里给出了一个例子:https://gobyexample.com/sorting-by-functions

以下是您可以为您的示例按键排序的方法:http://play.golang.org/p/i6-e4I7vih

import (
    "fmt"
    "sort"
)

type Pair struct {
    Key   string
    Value int
}

type ByKey []Pair

func (s ByKey) Len() int {
    return len(s)
}

func (s ByKey) Swap(i, j int) {
    s[i], s[j] = s[j], s[i]
}

func (s ByKey) Less(i, j int) bool {
    return s[i].Key < s[j].Key
}

func main() {
    pairs := []Pair{{"a", 1}, {"b", 0}, {"c", 2}}
    // Sort by Key
    sort.Sort(ByKey(pairs))
    fmt.Println(pairs) // [{a 1} {b 0} {c 2}]
}