05 / 08

How do generics (Go 1.18+) change API and library design? Where would you use or avoid them?

Generics allow writing type-safe functions and data structures that work across multiple types without code duplication or runtime reflection, but should complement rather than replace interfaces.

Generic utility functions
Use generics for
  1. 1

    Generic collections: typed stacks, queues, sets, linked lists

  2. 2

    Functional utilities: Map, Filter, Reduce, Contains, Keys, Values

  3. 3

    Typed repository or service interfaces to avoid repeated boilerplate

  4. 4

    Type-safe event bus or pub/sub systems

  5. 5

    Constraint-based numeric or ordered operations

Avoid generics when
  1. 1

    Runtime polymorphism with interfaces is sufficient and clearer

  2. 2

    The type set is open-ended — new types should satisfy behavior via interfaces, not constraints

  3. 3

    Constraints become so complex they hurt readability more than they help

  4. 4

    You need method type parameters — Go does not support them, only function and type-level generics