Generics in Go
From the Go cheat sheet · Generics · verified Jul 2026
Generics
Generic functions and types with type parameters
go
// Generic function
func Map[T any, U any](s []T, f func(T) U) []U {
result := make([]U, len(s))
for i, v := range s {
result[i] = f(v)
}
return result
}
// Constrained generic
func Min[T int | float64 | string](a, b T) T {
if a < b { return a }
return b
}🎯 Available since Go 1.18 — use any for unconstrained types
💡 ~ means underlying type (e.g., ~int matches type MyInt int)
📌 comparable constraint allows == and != operations
⚡ Type inference often lets you omit type arguments at call site