我知道如何根据数据类型对键/值进行排序:
map[1:a 2:c 0:b]
使用 GoLang 的 sort
包。我如何对 Pair
进行排序,如下所示:
[{c 2} {a 1} {b 0}]
我希望整对根据键或值排序?最终结果:
[{a 1} {b 0} {c 2}]
这是根据键排序的。以下是根据值排序:
[{b 0} {a 1} {c 2}]
最佳答案
您可以为自定义类型实现 Len
、Swap
和 Less
。这里给出了一个例子: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}]
}
关于sorting - 在 GoLang 中排序对,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29693708/