Sobes.tech
Junior — Middle

If you walk through the Map several times, will the sequence of keys be preserved?

sobes.tech AI

Answer from AI

In Go, the map type does not guarantee the preservation of key order during iteration. Each time you iterate over a map, the order of key traversal can be different because the internal representation of the hash table is unordered.

If you need to preserve order, for example, insertion order, you should use an additional data structure, such as a slice of keys, and iterate over it.

Example:

m := map[string]int{"a": 1, "b": 2, "c": 3}
keys := []string{"a", "b", "c"}

for _, k := range keys {
    fmt.Println(k, m[k])
}

Thus, the traversal sequence will be stable and predictable.