Junior — Middle
Does the Map data structure guarantee the preservation of insertion order of elements?
sobes.tech AI
Answer from AI
In the Go language, the map data structure does not guarantee the preservation of insertion order of elements. Iteration over a map occurs in a random order, which may change with each traversal.
If you need to preserve the insertion order, you should use an additional data structure, such as a slice to store keys in the desired order, or use third-party libraries that implement ordered dictionaries.
Example of iterating over a map while preserving the order of keys:
package main
import "fmt"
func main() {
m := map[string]int{"a": 1, "b": 2, "c": 3}
keys := []string{"a", "b", "c"} // insertion order
for _, k := range keys {
fmt.Println(k, m[k])
}
}