在值上映射排序(Struct的属性)

问题描述 投票:-1回答:1

我有以下地图:

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()方法来获取排序结果。我需要添加更多代码吗?

sorting go struct
1个回答
1
投票

Go中的map类型是无序的。无论您对地图执行什么操作,下次迭代时都会以随机顺序接收密钥。因此,没有办法“排序”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)
}
© www.soinside.com 2019 - 2024. All rights reserved.