Skip to content

Adopting Go generics in production code — when, where, and how

Decide where generics actually help in Go services — slice/map utilities, type-safe stores, constraint sets — and where they make code worse than the interface alternative.

Go 1.18 added generics in March 2022, and four years later the question is no longer “are they ready” but “where should I use them”. This article is the decision framework Stack Harbor uses on production Go code — what generics legitimately improve, what they make worse, and which constraints are worth memorizing.

How to verify

A generic function compiles and substitutes types at every call:

package main

import (
    "fmt"
    "cmp"
    "slices"
)

func main() {
    ns := []int{3, 1, 4, 1, 5, 9, 2, 6}
    slices.Sort(ns)
    fmt.Println(slices.BinarySearchFunc(ns, 4, cmp.Compare))

    ss := []string{"go", "is", "back"}
    slices.Sort(ss)
    fmt.Println(ss)
}

slices.Sort is generic — same source, two type instantiations. The stdlib slices, maps, and cmp packages (Go 1.21+) are the canonical examples of where generics earn their place.

What’s happening

A generic function carries type parameters in square brackets: func Map[T, U any](xs []T, f func(T) U) []U. The compiler synthesizes a specialized version per instantiation (per distinct GC shape, roughly), so call sites pay no runtime overhead for the abstraction. Constraints (comparable, cmp.Ordered, or your own interface) bound what operations are legal on T.

Generics are valuable for:

  • Collections and combinators — Map, Filter, Reduce, slices.Sort, slices.Contains, maps.Keys. Code that operated as interface{} plus type assertions becomes type-safe and faster.
  • Type-safe stores — A Cache[K comparable, V any] keyed by typed keys is clearer than Cache[interface{}, interface{}].
  • Numeric and comparable utilities — Min[T cmp.Ordered], Sum[T constraints.Number]. The constraint expresses what was previously documentation.

Generics are NOT valuable for:

  • Interfaces with behavior. A Stringer interface lets you accept anything that has .String() string. Forcing that through a generic is more code and worse error messages.
  • Type erasure as a goal. A func Process(any) that does no operations on the value is just Process(any) — generics gain nothing.
  • Open-ended polymorphism. If the function needs to work on types that have no shared structural constraint, an interface is the right tool.

Decision

Use generics when all three are true:

  1. The type parameter is bounded by an operation (comparable, ordered, key-typed) — not just any.
  2. There are at least two real call sites with different types.
  3. The non-generic alternative is interface{} + reflection, or duplicated code.

Otherwise, prefer an interface or a concrete type.

The procedure

  1. Replace interface{} slice/map helpers with generics.

    // Before:
    func Contains(xs []interface{}, target interface{}) bool {
        for _, x := range xs { if x == target { return true } }
        return false
    }
    
    // After (or just use slices.Contains from stdlib):
    func Contains[T comparable](xs []T, target T) bool {
        for _, x := range xs { if x == target { return true } }
        return false
    }
  2. Generic Map / Filter / Reduce.

    func Map[T, U any](xs []T, f func(T) U) []U {
        out := make([]U, len(xs))
        for i, x := range xs { out[i] = f(x) }
        return out
    }
    
    func Filter[T any](xs []T, keep func(T) bool) []T {
        out := make([]T, 0, len(xs))
        for _, x := range xs { if keep(x) { out = append(out, x) } }
        return out
    }
    
    func Reduce[T, U any](xs []T, seed U, fold func(U, T) U) U {
        acc := seed
        for _, x := range xs { acc = fold(acc, x) }
        return acc
    }
  3. Use cmp.Ordered for numeric/string utilities.

    import "cmp"
    
    func Min[T cmp.Ordered](a, b T) T {
        if a < b { return a }
        return b
    }
    
    func Clamp[T cmp.Ordered](v, lo, hi T) T {
        if v < lo { return lo }
        if v > hi { return hi }
        return v
    }
  4. Type-safe store/cache.

    type Cache[K comparable, V any] struct {
        mu sync.RWMutex
        m  map[K]V
    }
    
    func NewCache[K comparable, V any]() *Cache[K, V] {
        return &Cache[K, V]{m: make(map[K]V)}
    }
    
    func (c *Cache[K, V]) Get(k K) (V, bool) {
        c.mu.RLock(); defer c.mu.RUnlock()
        v, ok := c.m[k]; return v, ok
    }
    
    func (c *Cache[K, V]) Set(k K, v V) {
        c.mu.Lock(); defer c.mu.Unlock()
        c.m[k] = v
    }

    Each call site instantiates the right type — *Cache[string, User], *Cache[uuid.UUID, *Order] — without interface{} casts.

  5. Constraint sets (your own). When the stdlib constraint is not enough:

    type Number interface {
        ~int | ~int32 | ~int64 | ~uint | ~uint32 | ~uint64 | ~float32 | ~float64
    }
    
    func Sum[T Number](xs []T) T {
        var sum T
        for _, x := range xs { sum += x }
        return sum
    }

    The ~ prefix matches types whose underlying type is the listed one — so type Cents int64 still satisfies Number.

  6. Errors and result types — usually NO. A generic Result[T any] modeled after Rust’s adds a layer of indirection without solving anything Go’s error returns don’t already solve. Idiomatic Go is (T, error) — keep it.

  7. Method type parameters — not allowed. Methods cannot declare new type parameters. If you need that, make the receiver generic and use a method that uses the parameter from the receiver. Often a top-level function is clearer.

Common pitfalls

  • Over-generification. A function that takes [T any] and never uses any operation on T is just func(any) with extra ceremony. Either constrain or drop the parameter.
  • Error messages get long. cannot use ... (variable of type X[int]) as Y[string] in argument becomes harder to scan when you nest generics. Type-alias the instantiations: type IntCache = Cache[int, *User].
  • comparable is not ==-safe for all interfaces. A type containing an interface field is comparable at compile time but panics at runtime if the interface holds an uncomparable concrete value (a slice, a map). Test the edges.
  • Performance is not free. Per-instantiation specialization keeps things fast, but inlining behavior changes and PGO interactions differ from non-generic code. Profile before committing to a generic hot path.
  • any is just an alias for interface{}. func Print[T any](x T) is functionally the same as func Print(x any) if you do nothing with T — the generic version forces inference but adds no safety.

Stack Harbor reviews generic code adoption case-by-case during operations engagements — most of our wins are in stdlib slices / maps adoption and a small number of type-safe stores. See how that fits into our managed operations practice when a Go codebase needs a design pass.