Skip to content

Checkpoint: Group Records by Key

The Course
•
30 min study

This checkpoint combines both halves of today. You will write one generic function that groups any kind of record, and let the caller decide, with a function value, which part of each record is the key. Grouping by a key the caller chooses is a common need in reports and summaries. The project's ledger doesn't group records this way, but today's ideas reappear when the ledger hands parsing work to a generic worker pool.

What you will use

  • Two type parameters. T is the record type and can be anything. K is the key type and must be comparable, because it becomes a map key.
  • A function parameter. key func(T) K extracts the key from one record. The grouping function never knows what a record contains.
  • A map of slices. map[K][]T holds each group. Appending to a missing key works, because the zero value of a slice is an empty slice.
  • A deterministic report. Map iteration order is unspecified, so sort the keys before printing.

Plan before you type

  1. Write the signature: func groupBy[T any, K comparable](items []T, key func(T) K) map[K][]T.
  2. Loop once over the items, compute each key, and append the item to its group.
  3. Define a small record type for the check, such as an order line with an item and a quantity.
  4. Call groupBy with a function literal that returns the item name.
  5. Collect the keys, sort them with slices.Sort, and print each key with the size of its group and the total quantity.
Prove the grouping keeps order

Within one group, the records should appear in the order they had in the input. Put two lines for the same item far apart in your input, and check that the group lists them in that order. If they come out reversed, something is prepending instead of appending.

Mistakes worth checking for

  • invalid map key type K: the key type parameter is constrained by any instead of comparable.
  • The groups print in a different order on different runs: the report ranges over the map instead of over sorted keys.
  • Every group is empty: the code appends to a copy, for example group := groups[k]; group = append(group, item), without storing group back in the map.
  • The grouping function compares records directly: it does not need to, and doing so would force T to be comparable too.
Exercise

Your turn

Write groupBy[T any, K comparable](items []T, key func(T) K) map[K][]T. Group these order lines by item: tent 2, drill 1, tent 3, lamp 4, drill 2. Print each item in name order with its number of lines and total quantity. Then group the same lines by whether the quantity is at least 3, to show that the key can have a different type.

The output should be:

Text
drill: 2 lines, 3 units
lamp: 1 lines, 4 units
tent: 2 lines, 5 units
At least 3: [{tent 3} {lamp 4}]
Smaller: [{tent 2} {drill 1} {drill 2}]
Your working space Go
package main

type Line struct {
	Item     string
	Quantity int
}

func main() {
	// Write groupBy, then group the lines twice.
}
Hint 1: the idea

Each item goes into the slice stored under its key. A missing key reads as a nil slice, and appending to a nil slice works, so no key needs setting up before its first item.

Hint 2: a first step

Write groupBy and the grouping by item first, and print the map to check it. For the second grouping the key function returns a bool, so K becomes bool and the map has at most two keys, true and false.

Worked solution
Run the solution Go
package main

import (
	"fmt"
	"slices"
)

type Line struct {
	Item     string
	Quantity int
}

func groupBy[T any, K comparable](items []T, key func(T) K) map[K][]T {
	groups := make(map[K][]T)
	for _, item := range items {
		k := key(item)
		groups[k] = append(groups[k], item)
	}
	return groups
}

func main() {
	lines := []Line{{"tent", 2}, {"drill", 1}, {"tent", 3}, {"lamp", 4}, {"drill", 2}}
	byItem := groupBy(lines, func(l Line) string { return l.Item })
	names := make([]string, 0, len(byItem))
	for name := range byItem {
		names = append(names, name)
	}
	slices.Sort(names)
	for _, name := range names {
		total := 0
		for _, l := range byItem[name] {
			total += l.Quantity
		}
		fmt.Printf("%s: %d lines, %d units\n", name, len(byItem[name]), total)
	}
	large := groupBy(lines, func(l Line) bool { return l.Quantity >= 3 })
	fmt.Println("At least 3:", large[true])
	fmt.Println("Smaller:", large[false])
}
Text
drill: 2 lines, 3 units
lamp: 1 lines, 4 units
tent: 2 lines, 5 units
At least 3: [{tent 3} {lamp 4}]
Smaller: [{tent 2} {drill 1} {drill 2}]

The same function grouped by a string key and then a bool key, and each group kept the input order. Printing large[true] and large[false] directly is deterministic, because it reads two known keys instead of ranging over the map.

Was this article helpful?

Your response is saved on this device.