This question already has an answer here:
Will this code always display the same result? Underlying question: will range
always iterate a map in the same order?
m := map[string]int {
"a": 1,
"b": 2,
"c": 3,
"d": 4,
"e": 5,
"f": 6,
}
for k, v := range m {
fmt.Printf("%v = %v", k, v)
}
</div>
No, it is intentionally randomized (to keep programmers from relying on it, since it is not specified in the language spec).
from the Go Blog
Iteration order
When 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 the release of Go 1.0, the runtime has randomized map iteration order. Programmers had begun to rely on the stable iteration order of early versions of Go, which varied between implementations, leading to portability bugs.
The answer is: No, it does not.
I wrote the following test to assert that.
func Test_GO_Map_Range(t *testing.T) {
originalMap := map[string]int {
"a": 1,
"b": 2,
"c": 3,
"d": 4,
"e": 5,
"f": 6,
}
getKeys := func(m map[string]int) []string{
mapKeys := make([]string, len(m))
i := 0
for n := range m {
mapKeys[i] = n
i++
}
return mapKeys
}
keys := getKeys(originalMap)
for i := 0; i < 5; i++ {
assert.Equal(t, keys, getKeys(originalMap))
}
}
I get results like:
Error: Not equal:
expected: []string{"d", "e", "f", "a", "b", "c"}
actual : []string{"a", "b", "c", "d", "e", "f"}
Error: Not equal:
expected: []string{"d", "e", "f", "a", "b", "c"}
actual : []string{"f", "a", "b", "c", "d", "e"}
Error: Not equal:
expected: []string{"d", "e", "f", "a", "b", "c"}
actual : []string{"c", "d", "e", "f", "a", "b"}
Error: Not equal:
expected: []string{"d", "e", "f", "a", "b", "c"}
actual : []string{"b", "c", "d", "e", "f", "a"}
Error: Not equal:
expected: []string{"d", "e", "f", "a", "b", "c"}
actual : []string{"a", "b", "c", "d", "e", "f"}