0Pricing
Go Academy · Lesson

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

  1. Type Parameters Syntax
  2. Constraints: comparable and interfaces
  3. Generic Data Structures
  4. Generics in Practice: Pitfalls
← Back to Go Academy