Go

When should you NOT use generics?

Question 131MediumGo 1.22 to 1.25

Interviewers want judgment, not enthusiasm. Guidance, broadly following Ian Lance Taylor's "When To Use Generics":

  • When you only call methods: if the function just calls r.Read(), take an io.Reader. A type parameter adds nothing.
  • When the implementation differs per type: use an interface with methods. Do not type-switch inside generic code.
  • When the operation needs reflection anyway: for example, encoding/json style struct walking.
  • Premature abstraction: write concrete code first. Introduce type parameters when you find yourself duplicating the same code for several types.
  • Hot paths with pointer-shaped method calls: they can be slower (see GC shapes).
  • Public APIs: a type parameter becomes part of the API. Changing its constraint later is a breaking change.
// Over-engineered
func WriteAll[W io.Writer](w W, data []byte) error { _, err := w.Write(data); return err }

// Idiomatic
func WriteAll2(w io.Writer, data []byte) error { _, err := w.Write(data); return err }

Good uses:

  • General-purpose data structures: trees, heaps, sets, caches.
  • Functions over slices, maps and channels of any element type: slices.Index, Merge, fan-in.
  • Numeric algorithms.
  • Type-safe wrappers such as atomic.Pointer[T] or a typed sync.Pool.

More on Generics

All 36 Generics questions