Golang Generics ([T any]) in 5 Minutes
Go generics for beginners, in five minutes, on a real Go program: why a Sum written for ints won't build for prices, what [T any] declares (a type parameter and its constraint), why Sum[T any] fails with 'operator + not defined', how int | float64 fixes it, how Go fills in T and checks every call before the program runs, why your own type Cents is refused and what ~int means, and how to read the standard library's generic slices.Max.
![Golang Generics ([T any]) in 5 Minutes, the full picture: diagram of Sum(prices), T = float64, float64: allowed, Sum[float64], Sum(counts), T = int, int: allowed, Sum, your code, Go, before your program runs](/img/golang-generics-t-any-in-5-minutes/map.jpg)
One Sum, two types
Your Go Sum adds up item counts, which are ints, but won't even build for prices, which are float64. In five minutes, generics give you one Sum for both.
![Sum(prices): one function, two ways: comparison table of func Sum(nums []int) int vs func Sum[T int | float64], go run., Sum(counts), Sum(prices), Functions to write, The type](/img/golang-generics-t-any-in-5-minutes/open.jpg)
The usual fix: copy it, and change int to float64. Now every bug fix has to be made twice. Go doesn't mind. It'll happily compile a third copy.
![The usual fix: another copy: code change of main.go, // SumFloats adds up a list of prices. (copy 2), func SumFloats(nums []float64) float64 { (int -> float64), var total float64 (every bug fix, made twice), Copy 3, SumInt64s: builds too](/img/golang-generics-t-any-in-5-minutes/copies.jpg)
T and its constraint
Add square brackets after the name, holding a type parameter, T. Like a normal parameter, but it holds a type, not a value, and Go fills it in at each call.
![func Sum[T any]: one function, T filled in later: diagram of func Sum[T any](nums []T) T {, Sum = one function, [T = type parameter T, []T) = nums: a list of T, T { = returns a T, T: filled in at each call](/img/golang-generics-t-any-in-5-minutes/anatomy.jpg)
After T comes its constraint: the set of types T may be. Any means every type at all. You might also see any written as interface, followed by empty curly braces. It means the same thing.
![[T any]: the constraint is a set of types: diagram of T, int, float64, string, bool, any: every type](/img/golang-generics-t-any-in-5-minutes/typeset.jpg)
So write Sum with T any, and call it on the counts and the prices. Guess first: does it build? No. Go stops with an error: it won't use plus on a value of type T. Any includes types you can't add, like bool, which is just true or false. So Go won't let you add a T at all.
sed -n '6,12p' main.gofunc Sum[T any](nums []T) T { var total T for _, n := range nums { total += n } return total }
go run .# cart ./main.go:9:3: invalid operation: operator + not defined on total (variable of type T constrained by any)
Go's own specification puts it this way: a constraint controls what you can do with T.
To get plus back, we need a constraint where every type can add. So replace any with int, a vertical bar, float64. The bar means or: T can be int or float64. Both can add, so plus is allowed. Run it: six items, and twenty-five fifty. One function, both lists.
sed -n '6p' main.gofunc Sum[T int | float64](nums []T) T {
go run .items: 6 total: $25.50
Picture a loading dock, with a sign at its gate. Every truck on the sign gets served: one dock, many trucks. The sign is the constraint. A truck that's not on it is turned away, before anything is unloaded.
How Go fills in T
Notice you never told Sum what T is. So how does Go know? You could spell it out, Sum, float64 in square brackets, but you rarely need to. Take Sum of prices. Go looks at the argument and sees float64. It checks float64 against the constraint. Then it builds a version of Sum just for float64. Sum of counts gets its own: T is int. All of it before your program runs.
Here's a mistake that could crash a checkout. Prices typed into a web form arrive as text. Pass that text to Sum, and the build stops: string isn't in the constraint, so Sum turns it away. Turned away at the gate.
sed -n '15,18p' main.go// prices typed into a web form arrive as text form := []string{"12.50", "8.25"} fmt.Println("form total:", Sum(form))
go build .# cart ./main.go:18:32: string does not satisfy int | float64 (string missing in int | float64)
Here's the old way, before generics: Sum takes a slice of any. Here, any isn't a constraint; it's the item type, so each item can hold anything. Inside, Sum insists each item is a float64. It builds, the text price slips in, and the program crashes while it runs: Go calls that a panic. Generics move that crash to build time.
![Text in the price list: when does Go stop it?: comparison table of SumAny(nums []any) vs Sum[T int | float64], The slice, any here, Each item, The check, go build, ./cart](/img/golang-generics-t-any-in-5-minutes/race.jpg)
Your own types
Real code often gives numbers their own type, like Cents for money, built on int, so you can't mix them up by accident. Guess first: will Sum take your discounts in Cents? No. Cents is built on int, but it isn't int. And the error even suggests the fix. It says: possibly missing tilde. A tilde is the small wavy line.
sed -n '5,6p;18,20p' main.go// Cents is an amount of money in whole cents. type Cents int discounts := []Cents{100, 50} fmt.Println("discounts:", Sum(discounts), "cents")
go run .# cart ./main.go:20:31: Cents does not satisfy int | float64 (possibly missing ~ for int in int | float64)
A tilde before a type means: any type built on it. So the constraint becomes: tilde int, a vertical bar, tilde float64. Run it: the counts and prices still add up, and the discounts too: a hundred and fifty cents.
sed -n '9p' main.gofunc Sum[T ~int | ~float64](nums []T) T {
go run .items: 6 total: $25.50 discounts: 150 cents
Before you write your own, check Go's slices package; a slice is Go's word for a list. Its Max is already generic, and you can read its signature now. Two type parameters. E is each item's type, and must be ordered: its values compare with less-than. S is the slice holding them; its tilde lets your own slice types in, like Cents. On your lists: three for the counts, twelve fifty for the prices.
go doc slices.Maxpackage slices // import "slices" func Max[S ~[]E, E cmp.Ordered](x S) E Max returns the maximal value in x. It panics if x is empty. For floating-point E, Max propagates NaNs (any NaN value in x forces the output to be NaN).
go run .most of one item: 3 priciest: $12.50
Recap
So: square brackets declare a type parameter, T. Its constraint lists the types T may be, and what you can do with them. Go fills in T at each call, and checks it before anything runs. A tilde lets your own types in.
![Go generics, in short: cards of [T any], The constraint, any: no +, int | float64, Checked at build, ~int](/img/golang-generics-t-any-in-5-minutes/recap.jpg)
If generics finally make sense, a like helps YouTube show this to more beginners, and subscribing keeps more Go idioms coming, five minutes at a time.
The lab and every command are linked in the description. Thanks for watching Cloud Explainers.
Sources
Demos: one container on our own Mac standing in for your laptop; the checkout and its numbers are made up. Every command, output and number was real. Watch the full video on YouTube.