Generics

Type parameters and constraints for reusable functions and data structures (Go 1.18+).

Since Go 1.18, functions and types can have type parameters. Generic code is written once for many types, with constraints saying what operations the types must support.

Generic functions and a generic ring buffer

Largest[T cmp.Ordered] works for ints, floats and strings.

Map[T, U any] and Filter[T any] transform and select from slices of any type.

Ring[T] is a generic type; NewRing[int](3) creates a ring of ints that keeps the last three values.

Making every function generic Use generics for data structures and algorithms that really repeat across types

Interfaces and plain functions remain the idiomatic choice when behaviour, not element type, varies.

What does the constraint cmp.Ordered allow?

Types that support < <= > >= : integers, floats and strings.