Golang map有序化

时间:2025-04-04 09:38:25

要使得Map有序化,我们必须要对map的key进行排序,我们可以使用函数对字符串进行排序。

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)
	}
	(names)
	for _, name := range names {
		("%s	%d
", name, slice1[name])
	}
}