Skip to content
Generics
step 1/5

Reading — step 1 of 5

Learn

~1 min readGenerics and Reflection

Go 1.18+ has generics: type parameters on functions and types.

go

The [T int | float64 | string] is a type constraint — T must be one of these.

Predefined constraints (golang.org/x/exp/constraints):

  • Orderedint, float, string (have <)
  • Integer — all int kinds
  • Float — float kinds
  • Numeric — int + float

any is the new alias for interface{} — generic without restriction:

go

Generic types:

go

Limits:

  • No method type parameters (only the receiver type's params are in scope)
  • Constraints can include underlying types: ~int matches int and any type whose underlying is int
  • Generics generate one specialization per usage — binary size grows

Use sparingly. Most Go code is concrete; reach for generics when:

  • You'd otherwise duplicate the same algorithm for 5+ types
  • You're writing a generic data structure
  • You're writing utility functions like Map/Filter/Reduce

Discussion

Ask a question, share an insight, or help someone who’s stuck.

Sign in to post a comment or reply.

Loading…