Sort Go map values by keys

后端 未结 6 625
悲哀的现实
悲哀的现实 2020-11-28 02:58

When iterating through the returned map in the code, returned by the topic function, the keys are not appearing in order.

How can I get the keys to be in order / sor

6条回答
  •  无人及你
    2020-11-28 03:25

    In reply to James Craig Burley's answer. In order to make a clean and re-usable design, one might choose for a more object oriented approach. This way methods can be safely bound to the types of the specified map. To me this approach feels cleaner and organized.

    Example:

    package main
    
    import (
        "fmt"
        "sort"
    )
    
    type myIntMap map[int]string
    
    func (m myIntMap) sort() (index []int) {
        for k, _ := range m {
            index = append(index, k)
        }
        sort.Ints(index)
        return
    }
    
    func main() {
        m := myIntMap{
            1:  "one",
            11: "eleven",
            3:  "three",
        }
        for _, k := range m.sort() {
            fmt.Println(m[k])
        }
    }
    

    Extended playground example with multiple map types.

    Important note

    In all cases, the map and the sorted slice are decoupled from the moment the for loop over the map range is finished. Meaning that, if the map gets modified after the sorting logic, but before you use it, you can get into trouble. (Not thread / Go routine safe). If there is a change of parallel Map write access, you'll need to use a mutex around the writes and the sorted for loop.

    mutex.Lock()
    for _, k := range m.sort() {
        fmt.Println(m[k])
    }
    mutex.Unlock()
    

提交回复
热议问题