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):
Ordered—int,float,string(have<)Integer— all int kindsFloat— float kindsNumeric— 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:
~intmatchesintand 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…