1. Stable output and map
If you are just getting started, it may seem that output order is just a matter of aesthetics: “well, all elements were printed, so what does the order matter?” The problem is that order suddenly becomes important in two cases: when you compare results by eye (“what changed?”) and when results are compared programmatically (autograder tests, scripts, checking systems).
Imagine that you are writing a small utility that prints statistics: how many times each word appeared, which tags are unique, which tasks are marked as completed. You run the program twice with the same input and expect the same text. If the order of lines “floats,” both people and tests start getting nervous. And nervous tests are like a nervous cat: it may knock everything off the table just because “it feels like it today.”
map is printed in “random” order
When we do:
for k, v := range m {
fmt.Println(k, v)
}
we get a correct traversal: all key → value pairs will be visited exactly once each (if you do not modify the map during traversal). But the traversal order is not part of the contract. This means you cannot write logic like “the first key is the smallest” or “the last key is the newest.” A map in Go has no notion of “first” or “last.”
There is an important practical nuance here: even if today you happen to get nicely sorted output, that is not a promise. Tomorrow, another run, another environment, another version — and the order is already different. In the official compatibility materials for Go, there is a separate example where a change in the sorting implementation between versions changed the order of equal elements, and programs that “expected a specific output” broke because of it.
So we take a simple rule from this: if order matters to a person or to tests, then the order must be specified explicitly.
Basic recipe: “keys → sort → print”
The easiest and most convenient way to “order” a map sounds almost like a cooking recipe, except the pot is a slice. We do this: collect all keys into a separate slice, sort that slice, and then print values strictly in the order of the sorted keys. So we are not sorting the map itself directly — that is not possible — but the slice of keys.
To keep the picture in your head, you can imagine it like this:
flowchart TD
A[map: key -> value] --> B["collected keys into []K"]
B --> C["sorted []K"]
C --> D["for _, k := range keys: print k and m[k]"]
Now to the code. Let’s start with a small scaffold for our example: a mini program that counts word frequencies (a frequency dictionary). This is convenient because map[string]int demonstrates both a “counter” and the need for stable output.
2. Sorting simple keys in the sort package
When keys are strings or numbers, the easiest approach is to use the sort package. It is old, reliable, like a grandfather who grumbles but always comes to fix the sink.
Example: printing map[string]int in alphabetical order
We count words and print frequencies. First we will show unstable output (what not to do), and then fix it.
package main
import "fmt"
func main() {
counts := map[string]int{"go": 3, "map": 1, "sort": 2}
for w, c := range counts {
fmt.Println(w, c) // order is not guaranteed
}
}
Now we make the output stable: collect keys, sort them, print them.
package main
import (
"fmt"
"sort"
)
func main() {
counts := map[string]int{"go": 3, "map": 1, "sort": 2}
keys := make([]string, 0, len(counts))
for k := range counts {
keys = append(keys, k)
}
sort.Strings(keys)
for _, k := range keys {
fmt.Println(k, counts[k]) // go 3 / map 1 / sort 2 (always the same)
}
}
Here, make([]string, 0, len(counts)) is especially useful: we reserve capacity for all keys right away and do not make append expand the buffer unnecessarily. This is not “optimization for the sake of optimization,” just neatness.
Example: if keys are numbers (sort.Ints)
Sometimes the key is not a string but, for example, an ID. The recipe is exactly the same; only the key type and the sorting change.
package main
import (
"fmt"
"sort"
)
func main() {
m := map[int]string{10: "ten", 2: "two", 7: "seven"}
keys := make([]int, 0, len(m))
for k := range m {
keys = append(keys, k)
}
sort.Ints(keys)
for _, k := range keys {
fmt.Println(k, m[k]) // 2 two / 7 seven / 10 ten
}
}
Important point: stability appears here because the keys are unique. If keys are unique, even an “unstable sort” still produces the same result, because there are no equal elements to swap around.
3. Sorting by a rule: sort.Slice
Very quickly, you will want not just “alphabetical order” but “by meaning.” For example: print words by descending frequency, and if the frequencies are equal, by alphabet. Or print strings by length. Or print numbers so that even ones come first, then odd ones.
For such cases, the sort package has an all-in-one tool: sort.Slice. It sorts any slice if you give it a comparison rule in the form of a function less(i, j int) bool.
Under the hood, the idea is simple: “element with index i should come before element j if less(i, j) == true.”
Example: sort strings by length and add a tie-breaker
package main
import (
"fmt"
"sort"
)
func main() {
words := []string{"go", "gopher", "map", "slices"}
sort.Slice(words, func(i, j int) bool {
if len(words[i]) != len(words[j]) {
return len(words[i]) < len(words[j])
}
return words[i] < words[j] // tie-breaker for determinism
})
fmt.Println(words) // [go map gopher slices]
}
Pay attention to the second branch: return words[i] < words[j]. This is a tie-breaker (a rule for equal elements). It is very important if you want truly deterministic output.
Why is this important? Because different versions and different sorting implementations may reorder elements that are considered equal by your main criterion in different ways. In the Go compatibility materials, it is stated directly that changes in the sorting implementation can change the order of equal elements, and you should not rely on the “random order of equals.”
Example: sorting map keys by values
Let us return to our map[string]int counter. We want to print the most frequent word first. Since we cannot sort a map, we sort the keys, but compare them through values in the map.
package main
import (
"fmt"
"sort"
)
func main() {
counts := map[string]int{"go": 3, "map": 1, "sort": 3}
keys := make([]string, 0, len(counts))
for k := range counts {
keys = append(keys, k)
}
sort.Slice(keys, func(i, j int) bool {
wi, wj := keys[i], keys[j]
if counts[wi] != counts[wj] {
return counts[wi] > counts[wj] // larger first
}
return wi < wj // order equal frequencies alphabetically
})
for _, k := range keys {
fmt.Println(k, counts[k])
}
}
Notice how carefully we make the tie-breaker: if frequencies are equal, we still define order using wi < wj. This turns the output into something “rock solid”: same input → same output.
4. The slices package: Sort and SortFunc
Starting with Go 1.21, the standard library got the slices package, which contains many convenient operations on slices, including sorting, and it is usually easier to read than combinations with sort.Interface. The release notes specifically mention that slices includes sorting functions and generally makes working with slices more convenient and “ergonomic.”
Today we are interested in two functions: slices.Sort (when elements are “orderable” — numbers, strings) and slices.SortFunc (when you need your own order).
slices.Sort: sorting strings and numbers “directly”
package main
import (
"fmt"
"slices"
)
func main() {
nums := []int{5, 2, 10, 2}
slices.Sort(nums)
fmt.Println(nums) // [2 2 5 10]
}
It is important to remember: slices.Sort sorts in place and returns nothing. This is a normal model for sorting: rearranging elements does not change the length of the slice, so returning a new slice is not necessary.
By the way, the slices package also has functions that return a new slice (for example, removing a range). And a typical beginner mistake there is to ignore the return value. In the Go materials, these traps are discussed as well: slices.Sort(s) correctly does not return, but slices.Delete returns a new slice, and you cannot ignore the result.
slices.SortFunc: sorting with a comparator
sort.Slice asks for less(i, j) bool, while slices.SortFunc asks for a function comparing elements: cmp(a, b T) int.
The usual contract is:
- if a should come before b, return a negative number;
- if after — a positive number;
- if “equal” from the sorting point of view — 0.
Let’s sort strings by length as before, but via slices.SortFunc:
package main
import (
"fmt"
"slices"
)
func main() {
words := []string{"go", "gopher", "map", "slices"}
slices.SortFunc(words, func(a, b string) int {
if len(a) != len(b) {
return len(a) - len(b)
}
if a < b {
return -1
}
if a > b {
return 1
}
return 0
})
fmt.Println(words) // [go map gopher slices]
}
Yes, this is a few more lines than one might like, but the comparison logic now works directly with elements a and b, without indices. For beginners, that often reads more easily: you compare values, not “elements with index i.”
And again, pay attention: a tie-breaker is mandatory if you want a deterministic result. Return 0 only when the strings are truly equal; otherwise, it is better to resolve the order yourself.
5. Example: a frequency dictionary with stable output
Now let us put everything together into a small program that reads words from stdin, counts frequencies, and prints the result in a stable form. We will make two output modes: alphabetical and frequency-based. This is not a “full application,” but it is an honest piece of practice: you will see how a map turns into a neat, predictable report.
Reading words and counting
package main
import "fmt"
func main() {
counts := make(map[string]int)
for {
var w string
_, err := fmt.Scan(&w)
if err != nil {
break
}
counts[w]++
}
fmt.Println("unique:", len(counts)) // for example: unique: 3
}
Here we use fmt.Scan in a loop “until an error.” When the input ends (EOF), Scan returns an error, and we leave the loop. We do not go deep into error kinds; the fact itself is enough: “there is an error, so we have finished reading.”
Stable alphabetical output (sort.Strings)
package main
import (
"fmt"
"sort"
)
func printAlpha(counts map[string]int) {
keys := make([]string, 0, len(counts))
for k := range counts {
keys = append(keys, k)
}
sort.Strings(keys)
for _, k := range keys {
fmt.Println(k, counts[k])
}
}
This function is pleasant to call: it does not change the map, it just prints. And it always prints the same way.
Stable output by frequency (sort.Slice)
package main
import (
"fmt"
"sort"
)
func printByCount(counts map[string]int) {
keys := make([]string, 0, len(counts))
for k := range counts {
keys = append(keys, k)
}
sort.Slice(keys, func(i, j int) bool {
a, b := keys[i], keys[j]
if counts[a] != counts[b] {
return counts[a] > counts[b]
}
return a < b
})
for _, k := range keys {
fmt.Println(k, counts[k])
}
}
Even if two words appeared the same number of times, we still print them in one order (alphabetical). That small detail is exactly what turns a program into something “predictable.”
Call both outputs from main
package main
import "fmt"
func main() {
counts := map[string]int{"go": 3, "map": 1, "sort": 3}
fmt.Println("== alphabet ==")
printAlpha(counts)
fmt.Println("== by count ==")
printByCount(counts)
}
6. Typical mistakes in stable output and sorting
Mistake #1: “I sorted the keys, but I print with range over the map.”
This looks like this: you did sort.Strings(keys), but then accidentally wrote for k, v := range m { ... }. As a result, your keys are sorted, but they are not used at all, and the order starts “dancing” again. The correct idea here is simple: the sorted source of order is the slice keys, so you must print strictly with for _, k := range keys.
Mistake #2: no tie-breaker when sorting by a “secondary” criterion.
For example, you sort words by frequency and return counts[a] > counts[b], and if the frequencies are equal, you return false. Then equal elements may be rearranged however the implementation likes, and the output will be unstable. This is especially unpleasant because it “almost always works,” and then suddenly starts blinking in tests. Changes in the sorting implementation between Go versions can change the order of equal elements, and you cannot rely on that.
Mistake #3: expecting sorting to return a new slice and continuing to work with the old one.
Sorting functions in sort and slices modify the slice in place. So if you wanted to “preserve the original order,” first make a copy (for example, using append([]T(nil), s...)), and sort the copy. Also keep in mind that the slices package has functions that modify “in place” (for example, slices.Sort), and functions that return a new slice (for example, slices.Delete), and ignoring the result in the second case is a classic trap.
Mistake #4: trying to “sort a map.”
Sometimes a beginner looks for something like sort.Map(m) or tries to convert a map into a “sorted map.” In Go, there is no such thing in the basic form: map is a structure for fast key access, not for storing elements in order. If you need order, you define it on top of the map: keys into a slice, sort, print.
Mistake #5: the comparator in slices.SortFunc returns random stuff.
If the comparison function sometimes returns 1, sometimes -1 for the same values (or violates the common-sense rule “if a < b, then b > a”), sorting may behave strangely. Stick to the simple contract: negative means “earlier,” positive means “later,” zero means “equal.” And try to return 0 only when the elements are truly equal; otherwise it is better to resolve the order with a tie-breaker.
GO TO FULL VERSION