Go blog: Go maps in action有一个很好的解释。
原文链接:https://www.f2er.com/go/187457.htmlWhen iterating over a map with a range loop,the iteration order is
not specified and is not guaranteed to be the same from one iteration
to the next. Since Go 1 the runtime randomizes map iteration order,as
programmers relied on the stable iteration order of the prevIoUs
implementation. If you require a stable iteration order you must
maintain a separate data structure that specifies that order.
这里是我的修改版本的示例代码:
http://play.golang.org/p/dvqcGPYy3-
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