Skip to content
Lesson 3 of 7

Step 1 of 5 · Reading · ~2 min

Learn

Generics 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
  • Signed / Unsigned — the signed and unsigned int kinds

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
  • The compiler shares one instantiation per GC shape (all pointer types share one), so it is neither full C++-style monomorphization nor free — binary size and indirection both grow a little

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

A note on this course's grader

Everything above describes Go 1.18 and later. The sandbox that grades the exercises in this course runs Go 1.13, which predates type parameters: func Filter[T any](...) there is a syntax error, not a missing import. So the exercise below asks for the concrete, pre-generics version of Filter — which is exactly the code that generics exist to stop you writing once per element type. Write the []int one, feel the duplication you would need for []string and []float64, and you will know precisely what a type parameter buys.

Up nextReflectionGenerics and Reflection

Discussion

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

Sign in to post a comment or reply.

Loading…