A hands-on, no-jargon walkthrough of generics in Go: what problem they solve, the syntax, and the patterns you'll actually use. Each topic is a small, runnable Go program with a README that explains the "why," not just the "what" — the code is already self-documenting for that part.
Anyone who knows basic Go (functions, structs, slices, maps) but hasn't written generic code yet — whether you've never touched it, or you've read about it and just want to see it in working programs before using it yourself.
Go 1.18 or later (generics were introduced in 1.18). This repo is developed
against a recent Go release; nothing here uses anything newer than the
standard library's cmp package (Go 1.21+).
Each numbered folder is a standalone, runnable program. Read its
README.md first, then run it and read the output alongside main.go:
go run ./01-why-generics
go run ./02-type-parameters
go run ./03-constraints
go run ./04-generic-structs
go run ./05-map-filter-reduce
go run ./06-data-structures
go run ./07-numeric-toolkitThey're numbered in the order they're meant to be read — each one builds on ideas from the last.
| # | Topic | What you'll learn |
|---|---|---|
| 01 | Why Generics? | The problem generics solve: code duplication vs. losing type safety with interface{}. |
| 02 | Type Parameters | The [T Constraint] syntax, type inference vs. explicit instantiation, any vs comparable. |
| 03 | Constraints | Writing custom constraints with | unions, the ~ (approximation) element, and the standard library's cmp.Ordered. |
| 04 | Generic Structs | Type parameters on structs, methods on generic types, and why methods can't add new type parameters. |
| 05 | Map, Filter, Reduce | Generic, reusable slice transformations — the pattern you'll reach for constantly. |
| 06 | Data Structures | A generic Stack[T any] and Set[T comparable] — picking the constraint that matches what the code needs. |
| 07 | Numeric Toolkit | Min/Max/Sum/Average, and why picking the narrowest correct constraint matters. |
go build ./...
go vet ./...Found something unclear or have another generics pattern worth a topic folder? Issues and PRs are welcome .The goal of this repo is to be the easiest possible to Go generics, so clarity beats cleverness every time.