我有一个结构图,我通过将数据流式传输到Go程序来填充它。地图的更新方式类似于下面的示例。
填充了此结构映射后,根据结构中count字段的值对此映射进行排序的最佳(或好)方法是什么?
package main
type data struct {
count int64
}
func main() {
m := make(map[string]data)
m["x"] = data{0, 0}
if xx, ok := m["x"]; ok {
xx.count = 2
m["x"] = xx
} else {
panic("X isn't in the map")
}
}这个例子可以在这里运行:http://play.golang.org/p/OawL6QIXuO
发布于 2013-11-13 15:57:50
正如siritinga已经指出的,map的元素是没有排序的,所以你不能对它排序。
您可以做的是创建一个slice并使用sort包对元素进行排序:
package main
import (
"fmt"
"sort"
)
type dataSlice []*data
type data struct {
count int64
size int64
}
// Len is part of sort.Interface.
func (d dataSlice) Len() int {
return len(d)
}
// Swap is part of sort.Interface.
func (d dataSlice) Swap(i, j int) {
d[i], d[j] = d[j], d[i]
}
// Less is part of sort.Interface. We use count as the value to sort by
func (d dataSlice) Less(i, j int) bool {
return d[i].count < d[j].count
}
func main() {
m := map[string]*data {
"x": {0, 0},
"y": {2, 9},
"z": {1, 7},
}
s := make(dataSlice, 0, len(m))
for _, d := range m {
s = append(s, d)
}
// We just add 3 to one of our structs
d := m["x"]
d.count += 3
sort.Sort(s)
for _, d := range s {
fmt.Printf("%+v\n", *d)
}
}输出:
{计数:1大小:7}
{计数:2大小:9}
{计数:3大小:0}
编辑
更新了示例,以使用指针并包含映射,以便您既可以进行查找,又可以对切片进行排序。
https://stackoverflow.com/questions/19946992
复制相似问题