Sobes.tech
Junior

Do you think maps (map) in Go will be ordered?

sobes.tech AI

Answer from AI

By default, iterating over a map in Go does not guarantee the order of elements. The order may change with each iteration. This is due to how the internal data structures for maps are implemented to achieve high performance.

However, there are several ways to obtain a sorted iteration:

  1. Sorting the keys: Get all the keys of the map, sort them, and then iterate over the map using the sorted keys.

    // Example of sorting keys
    package main
    
    import (
    	"fmt"
    	"sort"
    )
    
    func main() {
    	m := map[string]int{
    		"b": 2,
    		"a": 1,
    		"c": 3,
    	}
    
    	keys := make([]string, 0, len(m))
    	for k := range m {
    		keys = append(keys, k)
    	}
    	sort.Strings(keys) // Sorting strings, there are also sort.Ints, etc.
    
    	for _, k := range keys {
    		fmt.Println(k, m[k])
    	}
    }
    
  2. Using data structures that guarantee order: If order is critical, you can use other data structures instead of maps or implement your own. For example, a list of key-value pairs maintained in a sorted state.

Thus, standard maps in Go are unordered, but order can be achieved with additional operations.