Generics
Use generics when they simplify repeated type-safe logic; avoid them when interfaces or concrete code are clearer.
Canonical guidance
- use generics for algorithms and data structures that genuinely repeat across types
- prefer plain interfaces or concrete types when they are simpler
- do not introduce type parameters purely for sophistication
Use when
- reusable containers
- helpers that operate the same way across element types
- removing real duplication without losing clarity
Avoid
- generic wrappers around single concrete use cases
- replacing ordinary interface-based design with needless type parameters
- unreadable constraints
Preferred pattern
func Index[S ~[]E, E comparable](s S, v E) int {
for i := range s {
if s[i] == v {
return i
}
}
return -1
}
Anti-pattern
- generic APIs whose only benefit is avoiding a handful of explicit overloads in application code
Explanation: This anti-pattern is tempting after learning generics, but abstraction without repeated use makes APIs harder to read without reducing real duplication.
Why
- generics are a tool for clarity and reuse, not a new default for all abstractions
Sources
- An Introduction To Generics - Robert Griesemer and Ian Lance Taylor
- When To Use Generics - Ian Lance Taylor