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.

GoData Integrity

Code

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

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:`.