Skip to content

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).

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) {
}

Source

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.

Source