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

Continue with Go

Save the full cheat sheet or work through every related task.

Back to the full Go cheat sheet