package main import "fmt" func main(){ sample := map[string]string{ "key1":"value1", "key2":"value2", "key3":"value3", } for i := 0;i<3;i++{ fmt.Println(sample) } }
上面的go代码仅打印一次map [string] string三次。
我希望它具有固定的输出,但它显示如下:
map[key3:value3 key2:value2 key1:value1] map[key1:value1 key3:value3 key2:value2] map[key2:value2 key1:value1 key3:value3]
变了!
而在python中:
#!/bin/env python #encoding=utf8 sample = { "key1":"value1", "key2":"value2", "key3":"value3", } for i in range(3): print sample
输出:
{'key3': 'value3', 'key2': 'value2', 'key1': 'value1'} {'key3': 'value3', 'key2': 'value2', 'key1': 'value1'} {'key3': 'value3', 'key2': 'value2', 'key1': 'value1'}`
您不能依靠获得密钥的顺序。语言规范说: “一个映射是一组无序的元素”,后来又说: “未指定映射的迭代顺序,并且不能保证每次迭代之间都相同。”