要使得Map有序化,我们必须要对map的key进行排序,我们可以使用sort.Strings函数对字符串进行排序。
package main
import (
"fmt"
"sort"
)
func main() {
slice1 := map[string]int{
"wangxiaoming": 12,
"liming": 11,
"fenglingling": 16,
"gaoxiao": 15,
"shengyun": 14,
}
var names []string
for name := range slice1 {
names = append(names, name)
}
sort.Strings(names)
for _, name := range names {
fmt.Printf("%s %d
", name, slice1[name])
}
}