Senior
Does map guarantee the order of data reading?
sobes.tech AI
Answer from AI
In Go, the built-in map type does not guarantee the order of element traversal when reading. Iteration over a map occurs in a pseudo-random order, which may change with each program run. If a sorted traversal is needed, you should additionally store the keys in a slice and sort them before iteration.
Example of iterating over a map with sorted keys:
m := map[string]int{"b": 2, "a": 1, "c": 3}
// Get the keys
keys := make([]string, 0, len(m))
for k := range m {
keys = append(keys, k)
}
// Sort the keys
sort.Strings(keys)
// Iterate over the sorted keys
for _, k := range keys {
fmt.Println(k, m[k])
}