golang对map排序
golang中map元素是随机无序的,所以在对map range遍历的时候也是随机的,不像php中是按顺序。所以如果想按顺序取map中的值,可以采用以下方式:
import ( "fmt" "sort" ) func main() { m := make(map[int]string) m[1] = "a" m[2] = "c" m[0] = "b" //拿到key var keys []int for k := range m { keys = append(keys, k) } //对key排序 sort.Ints(keys) //根据key从m中拿元素,就是按顺序拿了 for _, k := range keys { fmt.Println("Key:", k, "Value:", m[k]) } }