Sobes.tech
Junior — Middle

Kas programmeerimiskeeles Map-andmete struktuur on sorteeritav võtmepõhiselt?

sobes.tech AI

Vastus AI-lt

In the Go language, the built-in data structure map does not guarantee sorting by keys. The order of traversal of elements in a map is random and can change between iterations.

If you need to sort elements by keys, you should extract the keys into a slice, sort it using sort, and then traverse the map in the order of the sorted keys:

keys := make([]string, 0, len(m))
for k := range m {
    keys = append(keys, k)
}
sort.Strings(keys)
for _, k := range keys {
    fmt.Println(k, m[k])
}

Thus, the map itself is not sorted, but sorting can be implemented manually.