By Abhijith N M · Reviewed 24 October 2026 · Editorial standards
Relay's reports count events by service and by level. The first version usually has two loops that differ only in the field they read. This lab extracts a typed countBy helper and a typed sortedKeys helper, then removes the duplication. The decision rule from step 12 applies: the algorithm is identical, only the element and key types vary, so generics are the right tool.
The refactor has a second lesson: the call site stays readable. countBy(events, func(e event) string { return e.Service }) names the key from the caller's perspective, and sortedKeys keeps output deterministic. If adding the generic helper had made call sites longer or hid the behavior, the concrete code would have been better.
countBy[T any, K comparable](items []T, key func(T) K) map[K]int.package main
import (
"cmp"
"fmt"
"maps"
"slices"
)
type event struct {
Service string
Level string
}
func countBy[T any, K comparable](items []T, key func(T) K) map[K]int {
counts := make(map[K]int, len(items))
for _, item := range items {
counts[key(item)]++
}
return counts
}
func sortedKeys[K cmp.Ordered](counts map[K]int) []K {
return slices.Sorted(maps.Keys(counts))
}
func main() {
events := []event{
{Service: "api", Level: "info"},
{Service: "api", Level: "error"},
{Service: "worker", Level: "info"},
}
byService := countBy(events, func(e event) string { return e.Service })
fmt.Println("by service", sortedKeys(byService), []int{byService["api"], byService["worker"]})
byLevel := countBy(events, func(e event) string { return e.Level })
fmt.Println("by level", sortedKeys(byLevel), []int{byLevel["error"], byLevel["info"]})
byClass := countBy(events, func(e event) string {
if e.Level == "error" {
return "5xx"
}
return "2xx"
})
fmt.Println("by class", sortedKeys(byClass), []int{byClass["2xx"], byClass["5xx"]})
}| Before | After | What improved |
|---|---|---|
countByService(events) | countBy(events, serviceKey) | One implementation for every key |
countByLevel(events) | countBy(events, levelKey) | Duplicate loop deleted |
keys(m) returning []string | sortedKeys(m) generic | Works for any comparable key |
| Type assertions at call sites | Inference from the key function | No unsafe casts |
Untyped any maps | map[K]int | The compiler checks the key type |
Key takeaways
Refactor to generics only when the algorithm is identical and just the types vary.
Let the key function carry inference so call sites stay concrete and readable.
Generic helpers still need deterministic output: sort map keys before printing.
A third key function should fit without changing the helper.
Delete more code than you add, or revert to the concrete version.
Written and edited by the nexGenCoders team. Spotted a mistake? Tell us and we will fix it.
Don't lose this lesson
Create a free account to save your progress, keep your streak, and work toward a shareable certificate.