Group Slice Rows Into Map By Key
Collect slice rows into map[string][]T buckets keyed by a field, then sort the keys so grouped output stays stable across runs.
Code
package main
import (
"fmt"
"slices"
)
type LogLine struct {
Level string
Msg string
}
func main() {
lines := []LogLine{
{Level: "info", Msg: "boot"},
{Level: "warn", Msg: "slow query"},
{Level: "info", Msg: "ready"},
{Level: "error", Msg: "db timeout"},
{Level: "warn", Msg: "retry"},
}
// 按字段分组:map[string][]T,append 到该键的桶里
grouped := make(map[string][]string)
for _, line := range lines {
grouped[line.Level] = append(grouped[line.Level], line.Msg)
}
// map 遍历顺序随机:要稳定输出就先排序键位
levels := make([]string, 0, len(grouped))
for level := range grouped {
levels = append(levels, level)
}
slices.Sort(levels)
for _, level := range levels {
fmt.Printf("%s (%d): %v\n", level, len(grouped[level]), grouped[level])
}
}What happens in order
Group Slice Rows Into Map By Key is built around the function main.
for _, line := range lines is the loop that carries the per-item work.
Iteration is driven by for _, line := range lines and for level := range grouped.
Statements that matter
for _, level := range levels {
fmt.Printf("%s (%d): %v\n", level, len(grouped[level]), grouped[level])
}
for _, line := range lines {
grouped[line.Level] = append(grouped[line.Level], line.Msg)
}
for level := range grouped {
levels = append(levels, level)
}
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
- How do you run Group Slice Rows Into Map By Key?
- Execute it straight away — the program needs nothing beyond the runtime.
Report a problem with this exampleOpens a pre-filled issue on GitHub.