我有以下地图:
detail := make(map[string]*Log)
type Log struct {
Id []string
Name []string
Priority int // value could be 1, 2, 3
Message string
}
我想根据我的情况下结构的值对“细节”地图进行排序。这应按属性“优先级”排序。
例如,Log(struct的地图)可能具有类似于以下的值:
Z : &{[ba60] [XYZ] 3 "I am the boss"}
B : &{[ca50] [ABC] 2 "I am the Junior"}
U : &{[zc20] [PQR] 1 "I am the Newbie"}
我希望他们从增加的优先级顺序打印,即1到3
U : &{[zc20] [PQR] 1 "I am the Newbie"}
B : &{[ca50] [ABC] 2 "I am the Junior"}
Z : &{[ba60] [XYZ] 3 "I am the boss"}
我尝试使用sort并实现了Sort接口,但似乎仍然缺少某处的线索。所以,我实现了以下界面:
type byPriority []*Log
func (d byPriority) Len() int {
return len(d)
}
func (d byPriority) Less(i, j int) bool {
return d[i].Priority < d[j].Priority
}
func (d byPriority) Swap(i, j int) {
d[i], d[j] = d[j], d[i]
}
但是我应该如何在此地图上应用sort.Sort()方法来获取排序结果。我需要添加更多代码吗?
答案 0 :(得分:1)
Go中的map
类型是无序的。无论您对地图执行什么操作,下次迭代时都会以随机顺序接收密钥。因此,没有办法排序&#34; map
。
您可以做的是将地图的条目复制到可排序的切片中。
package main
import (
"fmt"
"sort"
)
type Log struct {
Id []string
Name []string
Priority int // value could be 1, 2, 3
Message string
}
type Entry struct {
key string
value *Log
}
type byPriority []Entry
func (d byPriority) Len() int {
return len(d)
}
func (d byPriority) Less(i, j int) bool {
return d[i].value.Priority < d[j].value.Priority
}
func (d byPriority) Swap(i, j int) {
d[i], d[j] = d[j], d[i]
}
func printSorted(detail map[string]*Log) {
// Copy entries into a slice.
slice := make(byPriority, 0, len(detail))
for key, value := range detail {
slice = append(slice, Entry{key, value})
}
// Sort the slice.
sort.Sort(slice)
// Iterate and print the entries in sorted order.
for _, entry := range slice {
fmt.Printf("%s : %v\n", entry.key, entry.value)
}
}
func main() {
detail := map[string]*Log{
"Z": &Log{[]string{"ba60"}, []string{"XYZ"}, 3, "I am the boss"},
"B": &Log{[]string{"ca50"}, []string{"ABC"}, 2, "I am the Junior"},
"U": &Log{[]string{"zc20"}, []string{"PQR"}, 1, "I am the Newbie"},
}
printSorted(detail)
}