Generics
Intermediate · Generics & Modern Go
Generics (Go 1.18+) let functions and types work over a set of types via type
parameters with constraints: func Map[T, U any](s []T, f func(T) U) []U.
Constraints are interfaces (e.g. any, comparable, constraints.Ordered).
Resources
Section titled “Resources”Exercises
Section titled “Exercises”generics1 compile
Section titled “generics1 compile”Write one function that works for any type.
Show hint
Generic functions prevent code duplication by allowing the same function to handle different types.
Types are defined using syntax like:
func FuncName[T any](value T) {
}generics2 compile
Section titled “generics2 compile”Constrain a generic to add numbers of any numeric type.
Show hint
Type mismatches in arithmetic operations are not allowed, but generics enable functions to handle different types while maintaining the same logic.
In Go, type constraints can be declared. For this exercise, the `Number` interface is an example.
Ensure you include the appropriate type signature.