Sorted Map Keys With maps.Keys And slices.Sorted
maps.Keys hands back an iterator and slices.Sorted collects it into a sorted slice, so stable map output needs no manual key collection loop.
Code
package main
import (
"fmt"
"maps"
"slices"
)
func main() {
statusCounts := map[string]int{
"shipped": 12,
"pending": 3,
"canceled": 1,
}
// maps.Keys 返回 iter.Seq:slices.Sorted 一行收集并排序,得到稳定键序
keys := slices.Sorted(maps.Keys(statusCounts))
for _, k := range keys {
fmt.Printf("%s=%d\n", k, statusCounts[k])
}
// 只要值时同理:maps.Values 加 slices.Sorted
fmt.Println("values:", slices.Sorted(maps.Values(statusCounts)))
}How it works
Sorted Map Keys With maps.Keys And slices.Sorted is built around the function main.
Iteration happens inside for _, k := range keys — everything outside it runs once.
Using it
Running the file prints labeled results such as values: — each operation’s effect is visible in the output.
Key statements
for _, k := range keys {
fmt.Printf("%s=%d\n", k, statusCounts[k])
}
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 Sorted Map Keys With maps.Keys And slices.Sorted print when run?
- The script runs standalone; its 1 labeled outputs include `values:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.