Reputation: 3548
How can I loop through a map on a constant order multiple times ?
In my go code I am looping through a map twice but the values are not appearing on the same order on both loops :
fieldMap := map[string]int{...}
First loop :
for k, _ := range fieldMap {...}
Second loop :
for _, v := range fieldMap {...}
Upvotes: 2
Views: 2632
Reputation: 784
Go makes sure that you cannot rely on a map's order as stated in this blog post https://blog.golang.org/go-maps-in-action#TOC_7.
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 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.
Ainar-G's answer is correct, but here is a variation of it while incorporating this answer... https://stackoverflow.com/a/27848197/3536948
keys := make([]string, len(m))
i := 0
for k, _ := range m {
keys[i] = k
i += 1
}
for _, k := range keys {
fmt.Println(m[k])
}
Playground: http://play.golang.org/p/64onPZNODm
Upvotes: 4
Reputation: 36229
Save the keys in the first loop and use them in the second loop:
keys := make([]string, 0, len(m))
for k, v := range m {
fmt.Println(k, v)
keys = append(keys, k)
}
for _, k := range keys {
fmt.Println(k, m[k])
}
Playground: http://play.golang.org/p/MstH20wkNN.
Upvotes: 4