When a generic is not needed

One concrete type, and an interface with behavior, are almost always clearer than a type parameter.

A generic is justified when the algorithm is the same, the data types differ, and you want to keep a concrete result. First, Max, slices.Clone, and maps.Clone are good examples. A bad example is func Do[T any](v T) any, which still type-asserts inside. It is worse than an ordinary function with an interface: longer, and no more honest.

If there is exactly one implementation and the type is known, write that type. func UserByID(id int64) (User, error) does not get better from [T ~int64]. The type parameter does not remove repetition here, because there is no repetition.

If what is shared is an action, you need an interface. Save(w io.Writer) reads immediately. Save[T Writer](w T) forces the reader to remember that Writer is a constraint, and it gives nothing beyond the interface if T is not used anywhere else.

Do not add type parameters for the sake of making an internal package "library-like". Internal code may know its own structs. A generalization that was never called with a second type is an abstraction in reserve. Its price is compiler hints that are harder for a colleague to read.

A good check: name two types the function is already needed with today. If the second type is hypothetical, leave the concrete code. A generic is added later, mechanically, once the copy-paste has appeared. Cutting an extra type parameter out of an API hurts more.

Practice

  1. One type

    A function looks up a user by int64, and the project has no other identifier type. Is a type parameter needed?

    • Yes, otherwise the API is not modern
    • No, int64 is enough
    • Yes, but the constraint must be any
    • An empty interface is needed instead of int64
  2. A parameter used once

    The signature func Save[T io.Writer](w T) error does not use T anywhere else. What is simpler?

    • Keep the generic. It is always faster than an interface
    • Replace it with a parameter io.Writer
    • Replace T with any
    • Return T from the function, even if that is error
  3. A generic is appropriate

    Mark the tasks where a type parameter is appropriate.

    • The minimum of two values, numbers or strings
    • A clone of a slice with the same element type
    • Writing bytes to io.Writer
    • Looking up one known type User by int64