Easy way to get the keys in a map in alphabetical order

前端 未结 2 1092
臣服心动
臣服心动 2021-02-01 01:45

In Go, what\'s the easiest way to get the keys in a map sorted alphabetically? This is the shortest way I can do it:

package main

import \"container/vector\"
im         


        
2条回答
  •  走了就别回头了
    2021-02-01 02:34

    That would be most elegant method:

    package main
    
    import (
        "fmt"
        "sort"
    )
    
    func main() {
        m := map[string]string{"b": "15", "z": "123123", "x": "sdf", "a": "12"}
        keys := make([]string, 0, len(m))
        for key := range m {
            keys = append(keys, key)
        }
        sort.Strings(keys)
        fmt.Println(keys)
    }
    

提交回复
热议问题