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.
Code
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
cURL to Python & Go ConverterTranslate curl CLI commands with headers, auth, JSON bodies, and timeouts into ready-to-run Python requests and Go net/http client code snippets.SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.
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:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.