Look at the code first:
Func Main () { m: = Make (map[int]string) m[1] = "A" m[2] = "B" m[3] = "C" for K, V: = range m { FMT . Println (k, v) } fmt. Println ("-----------------") mm: = Make (map[int]string) mm[1] = "A" mm[2] = "B" mm[3] = "C" for K, V: = range mm { fmt. Println (k, v) } fmt. Println ("-----------------") mmm: = Make (map[int]string) mmm[1] = "A" mmm[2] = "B" mmm[3] = "C" for k, V: = Range mmm { fmt. Println (k, V) }}
I initially thought that the output order of the elements was the same in the output of three times, but the results were as follows:
[[email protected] map]$ go run range.go1 A2 b3 c-----------------1 A2 b3 C-----------------3 C1 A2 b
Yes, one of the important features of map in Go is that when you iterate through the elements of a map multiple times through the range loop, although you are accessing the same map, the order in which the elements are accessed is not exactly the same in the two-time range. Of course, it's not entirely random . Starting with Go1, go iterates through a random position when range traverses the elements in the map.
Why do you do this? Because go designers think that there are programmers who assume that the sequence of elements in the same map is assumed to be the same, and that under the premise of this hypothesis, something will be done (I am, in this hypothesis, a lot of letters), and they think that the sequence of the elements in a map should not be assumed, So starting from Go1.0, the starting position of the range map is randomized.
In spite of the hole, but it makes me more to go a layer of goodwill, go designers in every detail is thoughtful, they try to maintain the rigor of language, create a complete auxiliary tools, for some ambiguous characteristics, impose constraints, only in this way, will prevent the application layer code in the strange Bug, Let go language users can use it with confidence.
Although go is less generic now, is this feature really necessary? Go says, at least for now, not so necessary!
A very important feature in Go map