Generics in Practice: Pitfalls
When to use generics and common mistakes
Over-genericising
Not every function needs to be generic. If there is only one concrete type ever used, a generic adds complexity without benefit. Prefer concrete types and refactor to generics when duplication appears.
Type assertion inside generics
You cannot type-assert or type-switch inside a generic function on the type parameter itself — generics are not templates. Use interfaces or the reflect package instead.
// WRONG:
func Foo[T any](v T) {
if x, ok := v.(int); ok { // compile error
}
}All lessons in this course
- Type Parameters Syntax
- Constraints: comparable and interfaces
- Generic Data Structures
- Generics in Practice: Pitfalls