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.

GoData Integrity

Code

gosnippet
37 lines
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

FAQ

How do you run Group Slice Rows Into Map By Key?
Execute it straight away — the program needs nothing beyond the runtime.