Group Records Into A Map Of Slices
Group a record slice by a computed key into map[string][]T, using the zero value of a missing key so no existence check is needed.
Code
package main
import (
"fmt"
"sort"
)
type Order struct {
ID string
Status string
}
func main() {
orders := []Order{
{"o-1", "shipped"},
{"o-2", "pending"},
{"o-3", "shipped"},
{"o-4", "cancelled"},
{"o-5", "pending"},
}
byStatus := make(map[string][]Order)
for _, o := range orders {
// 缺失键时 []Order 零值可直接 append,无需先判存在
byStatus[o.Status] = append(byStatus[o.Status], o)
}
statuses := make([]string, 0, len(byStatus))
for status := range byStatus {
statuses = append(statuses, status)
}
sort.Strings(statuses)
for _, status := range statuses {
fmt.Printf("%s: %d orders\n", status, len(byStatus[status]))
}
fmt.Println("pending first:", byStatus["pending"][0].ID)
}Inside the snippet
Structurally, expect the function main and nothing else.
Repetition is confined to for _, o := range orders — the rest of the file is straight-line.
Caveats
- Entirely standard-library — copy it in and it runs.
Putting it to use
Entry signature: func main()
Output lines are prefixed (pending first:), so each printed line stays traceable to the step behind it.
Core lines
for _, status := range statuses {
fmt.Printf("%s: %d orders\n", status, len(byStatus[status]))
}
for status := range byStatus {
statuses = append(statuses, status)
}
for _, o := range orders {
// 缺失键时 []Order 零值可直接 append,无需先判存在
byStatus[o.Status] = append(byStatus[o.Status], o)
}
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.Number FormatterFormat numbers with thousands grouping, fixed decimals, custom separators, and an optional prefix or suffix.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 Group Records Into A Map Of Slices print when run?
- Run it as a complete program — the output lines carry labels such as `pending first:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.