Map Sorted Iteration For Output

Iterate maps through sorted key slices because Go randomizes map order, so reports and golden-file tests need explicit ordering.

GoData Integrity

Code

gosnippet
29 lines
package main

import (
	"fmt"
	"sort"
)

func main() {
	services := map[string]int{
		"orders":  3,
		"billing": 1,
		"auth":    9,
	}

	// 直接 range:顺序随机,两次运行可能不同
	for name, workers := range services {
		fmt.Println("range:", name, workers)
	}

	// 需要稳定输出(报表/快照测试)时:排序键后再遍历
	names := make([]string, 0, len(services))
	for name := range services {
		names = append(names, name)
	}
	sort.Strings(names)
	for _, name := range names {
		fmt.Printf("sorted: %s=%d\n", name, services[name])
	}
}

Iterating a map in sorted order

Map Sorted Iteration For Output keeps everything in the function main.

Repetition is confined to for name, workers := range services — the rest of the file is straight-line.

Applying it

Output lines are prefixed (range:, sorted:), so each line keeps the record of the step behind it.

Statements that matter

for name, workers := range services {
	fmt.Println("range:", name, workers)
}
for name := range services {
	names = append(names, name)
}
for _, name := range names {
	fmt.Printf("sorted: %s=%d\n", name, services[name])
}

Interactive Tools for This Topic

FAQ

What does Map Sorted Iteration For Output print when run?
Running the file directly is enough — expect labeled output lines such as `range:`, `sorted:`.