Generic functions

Generic functions in Go allow writing type-flexible code using type parameters and constraints like cmp.Ordered.

Generic functions in Go are functions that operate on any type specified by a type parameter, allowing you to write reusable code without duplication.

func Max[T cmp.Ordered](a, b T) T {
	if a < b {
		return b
	}
	return a
}

// Usage:
fmt.Println(Max(1, 2))       // int
fmt.Println(Max("a", "b"))   // string

This feature, introduced in Go 1.18, lets you define functions like Max that work with int, string, or any other type satisfying the cmp.Ordered constraint.