Skip to main content

Generics

Learning objectives
  • Write generic functions and types with correct constraints (any, comparable, cmp.Ordered, unions with ~).
  • Build production-quality generic data structures (Set, TTL cache) and use the standard slices, maps, cmp and iter packages instead of hand-written loops.
  • Write and consume range-over-func iterators (iter.Seq, iter.Seq2, Go 1.23+), including error handling and early exit.
  • Explain how Go implements generics (GC-shape stenciling) and argue when not to use them.

TL;DR​

  • Generics (Go 1.18+) let functions and types take type parameters constrained by interfaces that describe type sets.
  • ~int64 means "any type whose underlying type is int64" — so your type AmountMinor int64 qualifies. Without ~, only int64 itself does.
  • comparable allows ==/map keys; cmp.Ordered (Go 1.21) allows <. Since Go 1.20 interface types satisfy comparable, which can panic at runtime if the dynamic value isn't comparable.
  • Prefer the standard library: slices, maps, cmp, the min/max/clear built-ins (Go 1.21), iterators via iter (Go 1.23).
  • Iterators are plain functions: func(yield func(V) bool). Stop when yield returns false; use iter.Seq2[T, error] to stream rows with errors.
  • Go compiles generics with GC-shape stenciling + dictionaries: all pointer types share one instantiation, so method calls through a type parameter are indirect and rarely inlined. Generics are not automatically faster than interfaces.
  • Use generics for data structures and algorithms over data; use interfaces for behaviour of dependencies. Avoid generic repositories and functional-programming towers.

Why it matters​

Before 1.18, a typed cache for product listings or an idempotency-key set meant one of: copy-paste per type, interface{} plus type assertions (runtime panics, boxing allocations), or code generation. In real services generics remove a class of bugs and boilerplate:

  • A TTL cache used for exchange rates, product prices and feature flags — one implementation, typed at each use site.
  • A Set for de-duplicating idempotency keys or SKUs in a batch import.
  • Batching helpers that chunk 100k ledger entries into inserts of 1,000.
  • Streaming iterators that walk a customer's transactions across pages for a statement, without loading a year of data into memory.
  • Typed helpers around sync/atomic.Pointer[T] for hot-reloaded configuration.

Interviewers ask about generics to see whether you can use them with restraint — senior Go reviewers reject more generic code than they accept.

Core concepts​

Type parameters and inference​

// Map applies f to every element.
func Map[T, U any](s []T, f func(T) U) []U {
out := make([]U, 0, len(s))
for _, v := range s {
out = append(out, f(v))
}
return out
}

ids := Map(orders, func(o Order) string { return o.ID }) // T, U inferred

Inference works from argument types (and, since Go 1.21, from more contexts such as generic functions passed as arguments). It does not work from the return type alone — Zero[T]() needs explicit instantiation: Zero[int]().

Generic types are instantiated before use: Set[string], TTL[string, Rate]. Inside generic code, var zero T gives you the zero value of the type parameter.

Constraints are interfaces describing type sets​

ConstraintAllowsExample use
anyany type; no operators except assignmentcontainers, Map, Filter
comparable==, !=, map keysSet[T], cache keys, dedup
cmp.Ordered<, <=, >, >= plus ==Max, sorting, binary search
~int64int64 and any defined type with underlying int64domain amounts: type AmountMinor int64
~int | ~int64 (union)arithmetic shared by all membersnumeric helpers
interface{ ~string; Valid() bool }string-based types that also have Valid()enums like type Currency string
// Integer covers built-in integers and domain types defined on them.
type Integer interface {
~int | ~int32 | ~int64 | ~uint32 | ~uint64
}

type AmountMinor int64 // satisfies Integer thanks to ~int64

// SumBy totals a field. Integer-only on purpose: money is never float.
func SumBy[T any, N Integer](items []T, f func(T) N) N {
var total N
for _, it := range items {
total += f(it)
}
return total
}

total := SumBy(lines, func(l Line) AmountMinor { return l.Amount })

Constraints that contain type unions (like Integer) can only be used as constraints, not as ordinary variable types.

The comparable caveat: since Go 1.20, comparable is satisfied by interface types such as any and error. Set[any] compiles, but inserting a []byte value panics at runtime with "hash of unhashable type". Keep keys concrete.

Generic types: Set and TTL cache​

package collections

import (
"iter"
"maps"
)

// Set is a set of comparable values. The zero value is not usable; use NewSet.
type Set[T comparable] map[T]struct{}

func NewSet[T comparable](items ...T) Set[T] {
s := make(Set[T], len(items))
for _, it := range items {
s[it] = struct{}{}
}
return s
}

func (s Set[T]) Add(v T) { s[v] = struct{}{} }
func (s Set[T]) Has(v T) bool { _, ok := s[v]; return ok }
func (s Set[T]) Len() int { return len(s) }
func (s Set[T]) All() iter.Seq[T] { return maps.Keys(s) }

A concurrency-safe TTL cache — the kind of thing used for FX rates or merchant configs:

package cache

import (
"sync"
"time"
)

type entry[V any] struct {
val V
expires time.Time
}

// TTL is a concurrency-safe cache with per-entry expiry.
// It is unbounded: add eviction before using it for user-controlled keys.
type TTL[K comparable, V any] struct {
mu sync.RWMutex
data map[K]entry[V]
ttl time.Duration
now func() time.Time // injectable for tests
}

func NewTTL[K comparable, V any](ttl time.Duration) *TTL[K, V] {
return &TTL[K, V]{data: make(map[K]entry[V]), ttl: ttl, now: time.Now}
}

func (c *TTL[K, V]) Get(k K) (V, bool) {
c.mu.RLock()
e, ok := c.data[k]
c.mu.RUnlock()
if !ok || c.now().After(e.expires) {
var zero V
return zero, false
}
return e.val, true
}

func (c *TTL[K, V]) Set(k K, v V) {
c.mu.Lock()
c.data[k] = entry[V]{val: v, expires: c.now().Add(c.ttl)}
c.mu.Unlock()
}

// GetOrLoad returns a cached value or calls load. Concurrent misses for the
// same key all call load; combine with singleflight to collapse them.
func (c *TTL[K, V]) GetOrLoad(k K, load func(K) (V, error)) (V, error) {
if v, ok := c.Get(k); ok {
return v, nil
}
v, err := load(k)
if err != nil {
var zero V
return zero, err
}
c.Set(k, v)
return v, nil
}

// Usage: rates := cache.NewTTL[string, decimal.Decimal](30 * time.Second)

For a real hot cache, bound it (LRU/size), sweep expired entries, and collapse concurrent misses with singleflight (see Concurrency Patterns and Caching).

Limitations to know:

  • Methods cannot declare their own type parameters. func (s Set[T]) Map[U any](...) is illegal; write a top-level func MapSet[T, U comparable](...).
  • No specialisation or overloading, no variadic type parameters.
  • Generic type aliases (type Cache[V any] = TTL[string, V]) are fully supported since Go 1.24.

The pointer-method constraint pattern​

Sometimes you need to call a pointer method on a T you allocate yourself (e.g. decoding). Constrain a second type parameter to "pointer to T with this method":

type Unmarshaler[T any] interface {
*T
UnmarshalBinary([]byte) error
}

func DecodeAll[T any, PT Unmarshaler[T]](raw [][]byte) ([]T, error) {
out := make([]T, len(raw))
for i, b := range raw {
if err := PT(&out[i]).UnmarshalBinary(b); err != nil {
return nil, fmt.Errorf("decode record %d: %w", i, err)
}
}
return out, nil
}

events, err := DecodeAll[LedgerEvent](rows) // PT inferred as *LedgerEvent

Standard library: slices, maps, cmp​

You should rarely write these loops by hand any more:

slices.SortFunc(txns, func(a, b Txn) int {
return cmp.Or(
a.BookedAt.Compare(b.BookedAt), // primary: time
cmp.Compare(a.ID, b.ID), // tiebreak: ID, for deterministic output
)
})

i, found := slices.BinarySearchFunc(txns, cutoff, func(t Txn, c time.Time) int {
return t.BookedAt.Compare(c)
})

skus = slices.Compact(slices.Sorted(slices.Values(skus))) // sort + dedup
hasVIP := slices.ContainsFunc(customers, func(c Customer) bool { return c.Tier == "vip" })
keys := slices.Sorted(maps.Keys(balances)) // deterministic iteration
for batch := range slices.Chunk(entries, 1000) { // Go 1.23
if err := repo.InsertBatch(ctx, batch); err != nil {
return err
}
}

cmp.Or (Go 1.22) returns its first non-zero argument — ideal for multi-key comparisons. min, max and clear are built-ins since Go 1.21.

Iterators: range-over-func (Go 1.23)​

An iterator is just a function that calls yield for each element:

package iter

type Seq[V any] func(yield func(V) bool)
type Seq2[K, V any] func(yield func(K, V) bool)

for v := range seq { ... } compiles into a call to seq with a synthesized yield whose body is the loop body. break, return or a panic in the loop makes yield return false, and the iterator must stop — calling yield again after it returned false panics at runtime.

A real use: stream a customer's transactions for a statement with keyset pagination, surfacing errors through Seq2:

// Transactions streams all transactions for an account, pageSize rows per query.
func (r *Repo) Transactions(ctx context.Context, accountID string, pageSize int) iter.Seq2[Txn, error] {
return func(yield func(Txn, error) bool) {
var afterID int64
for {
page, err := r.page(ctx, accountID, afterID, pageSize)
if err != nil {
yield(Txn{}, err)
return
}
for _, t := range page {
if !yield(t, nil) {
return // consumer stopped early
}
}
if len(page) < pageSize {
return
}
afterID = page[len(page)-1].ID
}
}
}

// Consumer:
for txn, err := range repo.Transactions(ctx, "acc_7", 500) {
if err != nil {
return fmt.Errorf("statement for acc_7: %w", err)
}
if err := w.WriteLine(txn); err != nil {
return err
}
}

Notes:

  • Push iterators (above) can be converted to pull style with iter.Pull, which returns next and stop functions — always defer stop().
  • Standard iterators: slices.All, slices.Values, slices.Backward, maps.Keys, maps.Values, maps.All, collectors slices.Collect, slices.Sorted, maps.Collect; Go 1.24 added strings.Lines, strings.SplitSeq, strings.FieldsSeq (and bytes equivalents).
  • Range over integers (for i := range 10) arrived earlier, in Go 1.22.
  • An iterator that holds resources (rows, files) should release them when it returns, whether the consumer finished or broke out early — a defer inside the iterator function does this.

How generics are implemented — and why it matters​

Go doesn't fully monomorphise like C++ or Rust, nor box everything like Java. It uses GC-shape stenciling with dictionaries: one copy of the code per "GC shape" (roughly, underlying memory layout), plus a hidden dictionary argument describing the concrete types.

  • Sum[int64] and Sum[AmountMinor] share a shape — and both are specialised for int64-shaped arithmetic, so they're fast.
  • All pointer types share one shape. Process[*Order] and Process[*Payment] use the same code; calls to methods on T go through the dictionary — an indirect call, often not inlined, and arguments may escape.
  • Consequence: a generic function calling methods via a constraint can be slower than a plain interface version or hand-specialised code. Measure (see Profiling & Performance).

When not to use generics​

Anti-patterns:

  • Generic repository Repository[T Entity] with Create/Get/Update/Delete. Real aggregates need different queries, locks and invariants (a ledger account is never "updated" generically). Write focused repositories per aggregate (see Domain-Driven Design).
  • Option/Result/Monad libraries that fight Go's (T, error) idiom.
  • Constraint gymnastics — five type parameters to save ten lines. Readability is a feature.
  • Generics instead of an interface for a single method call — func Notify[T Notifier](n T) buys nothing over func Notify(n Notifier).

Trade-offs​

OptionStrengthsWeaknessesChoose when
GenericsCompile-time type safety, no boxing for value types, one implementationComplex signatures; pointer-shaped instantiations dispatch indirectlyContainers, algorithms, typed helpers with 2+ real uses
InterfacesSimple, runtime polymorphism, easy fakesDynamic dispatch, boxing, type assertions to get data backBehaviour of dependencies (ports)
any + type assertionWorks with anythingRuntime panics, no compile-time safetyTruly heterogeneous data (JSON trees), legacy APIs
Code generationFully specialised, any shapeBuild step, generated code to reviewProtobuf/SQL mapping (sqlc), enums (stringer)
Copy-paste per typeSimple, specialisedDrift and bugs across copiesTwo tiny functions; generics would be harder to read
Iterators (iter.Seq)Lazy, composable, early exit, constant memoryHarder to debug; error handling via Seq2Streaming large or paginated data
SlicesSimple, random access, reusableMaterialises everything in memorySmall/medium results, need len or sorting

In practice​

  • Hot-reloadable config with a typed atomic pointer — no locks on the read path:
type Limits struct {
MaxTransferVND int64
DailyCapVND int64
}

var current atomic.Pointer[Limits]

func Reload(l *Limits) { current.Store(l) }
func Load() *Limits { return current.Load() }
  • Batch inserts with slices.Chunk keep each statement under the database's parameter limit (PostgreSQL caps a statement at 65,535 bind parameters).
  • Deterministic output for reports and signatures: slices.Sorted(maps.Keys(m)) before iterating.
  • Domain enums with ~string constraints let a helper accept Currency, Country and Channel types while rejecting raw strings.
  • Before writing a generic helper, search slices/maps/iter — most exist. Since Go 1.26, go fix runs "modernizer" analyzers (minmax, slicescontains, mapsloop, rangeint…) that rewrite older code to use them — run it with -diff first and review.

Common pitfalls​

  • Forgetting ~ — func Sum[T int64] rejects AmountMinor. Symptom: "AmountMinor does not satisfy int64".
  • comparable with interface types — Set[any] panics on unhashable values at runtime.
  • Trying to add methods with type parameters — compile error; use functions.
  • Ignoring yield's result — "range function continued iteration after function for loop body returned false" panic.
  • Dropping errors in iterators — a Seq[Txn] over a database silently truncates the statement on a network error. Use Seq2[Txn, error] or return a separate Err().
  • Assuming generics are faster — pointer-shaped type parameters with method calls may be slower than interfaces. Benchmark.
  • Generic everything — reviewers can't follow; onboarding slows. Keep generics at the leaves (utilities, containers).
  • Unbounded generic caches keyed by user input — memory leak and DoS vector.

Interview angle​

Typical questions: "What problem do generics solve that interfaces don't?", "What does ~ mean?", "comparable vs cmp.Ordered?", "Implement a generic Set / LRU cache", "How are generics implemented in Go and what are the performance implications?", "When would you reject a generic PR?"

A strong answer distinguishes data-shape abstraction (generics) from behaviour abstraction (interfaces), writes a correct Set[T comparable] with struct{} values, explains type sets and ~, mentions GC-shape stenciling and its effect on pointer types, and names concrete anti-patterns (generic repositories). Bonus: write a Seq2 iterator with proper early exit and error propagation.

Follow-ups: "Why can't methods have type parameters?" (it would require runtime instantiation or whole-program analysis for interface satisfaction), "How do you make a generic type safe for concurrent use?", "Pull vs push iterators?"

Red flags: wrapping every function in type parameters, generic repository designs, or believing generics are fully monomorphised.

Self-check​

1. Why does func Max[T int64](a, b T) T reject type AmountMinor int64, and how do you fix it?

A type-set element without ~ contains exactly that type. AmountMinor is a distinct defined type whose underlying type is int64. Use ~int64, or better cmp.Ordered, which already includes ~int64. (For max specifically, the built-in max exists since Go 1.21.)

2. Set[any] compiles. What can go wrong at runtime and why does Go allow it?

Since Go 1.20, interface types satisfy comparable because interfaces support == syntactically. If a dynamic value is not comparable (slice, map, func), hashing or comparing it panics at runtime. Use concrete key types.

3. Write the signature of an iterator streaming transactions with errors, and explain what the iterator must do when yield returns false.

func (r *Repo) Transactions(ctx context.Context, id string) iter.Seq2[Txn, error]. When yield returns false the consumer has broken out (or returned/panicked); the iterator must stop calling yield, release resources (close rows), and return. Calling yield again panics.

4. Explain GC-shape stenciling and its effect on Process[*Order] vs Process[int64].

The compiler emits one instantiation per GC shape and passes a dictionary of type information. int64-shaped instantiations get specialised arithmetic. All pointer types share one shape, so Process[*Order] and Process[*Payment] share code and call methods on T indirectly via the dictionary — similar cost to (sometimes worse than) interface dispatch.

5. A teammate proposes Repository[T Entity] with generic CRUD for all aggregates. What's your review?

Reject or narrow it: aggregates differ in queries, locking (SELECT ... FOR UPDATE on accounts), invariants and lifecycle (ledger entries are append-only). A generic CRUD layer encourages anemic models and leaks persistence concerns. Keep focused repositories per aggregate; generic helpers for scanning rows or batching are fine.

6. Scenario: you need the top 3 merchants by captured volume from a map[string]int64, deterministically. Which standard functions do you use?

Collect keys with slices.Collect(maps.Keys(m)), sort with slices.SortFunc comparing volume descending and then merchant ID ascending (cmp.Or of two cmp.Compare calls) for deterministic ties, and take keys[:min(3, len(keys))].

🧠 Flashcards0/9 learned · 0 retries

Exercise​

  1. Implement LRU[K comparable, V any] with Get, Put, Len, a capacity bound, and an All() iter.Seq2[K, V] that iterates most-recently-used first. Make it safe for concurrent use.
  2. Write Transactions(...) iter.Seq2[Txn, error] over an in-memory fake that pages 3 rows at a time; test early break (assert no further pages are fetched) and mid-stream errors.
  3. Benchmark SumBy against a hand-written loop and against an interface-based Amounter version (b.Loop, Go 1.24). Run benchstat on 10 runs of each and explain the result using GC shapes.
  4. Refactor one helper in your own codebase to use slices/maps/cmp and delete the old code.

Done when: tests pass with -race, the LRU never exceeds capacity, and you can explain the benchmark numbers.

Further reading​

  • Go blog: "An Introduction To Generics" (Robert Griesemer, Ian Lance Taylor).
  • Go blog: "When To Use Generics" (Ian Lance Taylor).
  • Go blog: "Range Over Function Types" (Ian Lance Taylor).
  • Go blog: "All your comparable types" (Robert Griesemer) — the Go 1.20 change.
  • Go design doc: "Generics implementation — GC Shape Stenciling".
  • Package docs: iter, slices, maps, cmp.
  • Teiva Harsanyi, 100 Go Mistakes and How to Avoid Them — "Being confused about when to use generics".
Finished this page?

Do the self-check first. Marking it complete schedules spaced reviews (1, 3, 7, 14, 30… days).