golang中map的排序

前端之家收集整理的这篇文章主要介绍了golang中map的排序前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

在实现 golang 中发布订阅模式的时候,需要按照优先级排序回调函数;golang 中的 map 是无序的,需要手动取出 key,并对key进行排序,下面是排序一块的代码段:

[
    1 => [func1,func2]
    0 => [func5,func6]
    2 => [func3,func4]
]

...

[func5,func6,func1,func2,func3,func4]
func (ed *eventdispatcher) SortListeners(event string) {
    ed.sorted[event] = nil
    // 发布订阅模式中函数执行的优先级
    priorities := make([]int,0)
    for priority,_ := range ed.listeners[event] {
        priorities = append(priorities,priority)
    }
    // 对优先级的数字进行排序
    sort.Ints(priorities)
    sorted := make([]func(interface {}) interface {},0)
    // 按照优先级顺序合并 map
    for _,priority := range priorities {
        sorted = append(sorted,ed.listeners[event][priority]...)
    }
    ed.sorted[event] = sorted
}
原文链接:https://www.f2er.com/go/190374.html

猜你在找的Go相关文章