Sobes.tech
Junior

What is the order of element traversal in a map?

sobes.tech AI

Answer from AI

The order of iteration over elements in map in Golang is not guaranteed and can change with each iteration. It is non-deterministic.

For example:

package main

import "fmt"

func main() {
	m := map[string]int{
		"apple":  1,
		"banana": 2,
		"cherry": 3,
	}

	// First iteration
	fmt.Println("First iteration:")
	for key, value := range m {
		fmt.Printf("%s: %d\n", key, value)
	}

	// Second iteration may produce a different order
	fmt.Println("\nSecond iteration:")
	for key, value := range m {
		fmt.Printf("%s: %d\n", key, value)
	}
}