Go Tutorial: Generics
Write functions and types once and use them with many types: type parameters, constraints like comparable and cmp.Ordered, custom constraints, generic types, and the slices and maps packages.
Write it once, for every type
Some code doesn't care what it is working with. Checking whether a list contains an item works the same for book titles and for publication years. A stack of returned books works the same as a stack of ticket numbers.
Before generics, Go made you either copy the code for each type or give up type safety. Generics let you write it once with a **type parameter**, a placeholder for a type, and let the compiler fill in the real type at each call.
You will write generic functions, restrict them with **constraints** so they can compare and sort, define your own constraint, and build a generic `Stack` type. Then you will meet the standard library's generic toolbox: the `slices` and `maps` packages and the built-in `min` and `max`.
What you'll learn in this Go generics tutorial
This interactive Go tutorial has 9 hands-on exercises. Estimated time: 30 minutes.
- One function, many types — Without generics, adding up a `[]int` and a `[]float64` takes two functions with identical bodies: `sumInts`, `sumFloats…
- comparable: types you can compare with == — Right now `Contains` only accepts strings, so the calls with `years` do not compile. Run it to see the error.
- Type inference and several type parameters — A function can have more than one type parameter. `Map[T, U any]` takes a slice of `T` and a function from `T` to `U`, a…
- cmp.Ordered: types you can sort — `comparable` gives you `==`, but not `<` or `>`. For those you need `cmp.Ordered` from the standard `cmp` package: it al…
- Your own constraint with ~ — A constraint is just an interface. Besides methods, a constraint interface can list the types it allows, separated by `|…
- Generic types: a Stack of anything — Types can have type parameters too. `Stack[T]` is a struct holding a `[]T`. When you use it, you choose the element type…
- The slices package — You don't have to write `Contains` yourself: the standard `slices` package is a collection of generic functions that wor…
- Sorted map keys with maps and slices — Map iteration order in Go is deliberately unpredictable, so to print a map in a stable order you sort its keys first.
- Built-in min and max — Go has built-in `min` and `max` functions. They take one or more arguments of any ordered type and need no import: `min(…
Go Generics concepts covered
- Write it once, for every type