按键排序golang映射值
当迭代通过主题函数返回的代码中的返回映射时,键不会按顺序显示。
我如何获得按顺序排序/排序的地图,使键的顺序和值对应? 这里是the code。
Go blog: Go maps in action有一个很好的解释。
这里是我的修改版本的示例代码: package main import ( "fmt" "sort" ) func main() { // To create a map as input m := make(map[int]string) m[1] = "a" m[2] = "c" m[0] = "b" // To store the keys in slice in sorted order var keys []int for k := range m { keys = append(keys,k) } sort.Ints(keys) // To perform the opertion you want for _,k := range keys { fmt.Println("Key:",k,"Value:",m[k]) } } 输出: Key: 0 Value: b Key: 1 Value: a Key: 2 Value: c (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |