The Go Programming Language Specification says:
3. The iteration order over maps is not specified. [...]
That\'s to be expected
Map is implemented in Go as a hashmap.
The Go run-time uses a common hashmap implementation which is implemented in C. The only implementation differences between map[string]T
and map[byte]T
are: hash function, equivalence function and copy function.
Unlike (some) C++ maps, Go maps aren't fully specialized for integers and for strings.
In Go release.r60, the iteration order is independent from insertion order as long as there are no key collisions. If there are collisions, iteration order is affected by insertion order. This holds true regardless of key type. There is no difference between keys of type string
and keys of type byte
in this respect, so it is only a coincidence that your program always printed the string keys in the same order. The iteration order is always the same unless the map is modified.
However, in the newest Go weekly release (and in Go1 which may be expected to be released this month), the iteration order is randomized (it starts at a pseudo-randomly chosen key, and the hashcode computation is seeded with a pseudo-random number). If you compile your program with the weekly release (and with Go1), the iteration order will be different each time you run your program. That said, running your program an infinite number of times probably wouldn't print all possible permutations of the key set. Example outputs:
stringMap keys: b 0 hello c world 10 1 123 bar foo 100 a
stringMap keys: hello world c 1 10 bar foo 123 100 a b 0
stringMap keys: bar foo 123 100 world c 1 10 b 0 hello a
...