System Design

G5

Generics

A type parameter lets one function work for many types, and the compiler checks each call. Here are the rules, the errors the compiler really prints, the code it really produces, and the measured cost.

Not startedSaved in this browser only.
  1. 1A constraint is a type set. The set decides which operators and methods the body may use.
  2. 2Use a type parameter when the code is the same for each type and a caller keeps the type. If a method is all you need, use an interface.
  3. 3Go compiles one body per GC shape and passes a dictionary. Value code stays fast; a method call on T costs about the same as an interface call.
  4. 4A generic method can take its own type parameters since Go 1.27, but it cannot implement an interface.
G5
    A

    The trap

    it compiles, then it panics
    a set of anythinggo
    package main
    
    import "fmt"
    
    type Set[T comparable] map[T]struct{}
    
    func (s Set[T]) Add(v T) { s[v] = struct{}{}2 }
    
    func main() {
      s := Set[any]{}1
      s.Add(1)
      s.Add("a")
      fmt.Println("len:", len(s))
      s.Add([]int{1})3
      fmt.Println("len:", len(s))
    }
    1. 1any satisfies comparable since Go 1.20, because two interface values can be compared. The compiler says nothing.
    2. 2The map hashes the key. The hash looks at the dynamic type.
    3. 3A slice has no hash, so this call panics. The panic comes from a line with no type error.
    key typerecorded outputstatus
    Set[any]panic: runtime error: hash of unhashable type []intRun-time panic
    Set[string]len: 2, len: 3Approved
    Set[[]int][]int does not satisfy comparableCompile error
    • comparable means "== compiles", not "== is always safe".
    • An interface type, or a struct that holds one, passes the check and can still panic.
    • comparable has no strict form that refuses interface types. Choose a concrete type argument.

    comparable accepts interface types since Go 1.20, so a Set of any can panic at run time. I use a concrete key type.

    B

    The model: shapes and dictionaries

    symbols read from a real binary
    call sitedictionary: one per type argumentmachine code: one per shapeDescribe[int].dict[int]Describe[MyInt].dict[MyInt]Describe[*A].dict[*A]Describe[*B].dict[*B]Describe[go.shape.int]int, MyIntDescribe[go.shape.*uint8]every pointer typeThe dictionary holds the real types and the method entries. The code reads them at run time.
    • Full stenciling makes one body per type. Boxing makes one body for all types. Go sits between them.
    • Two types have the same GC shape if they have the same underlying type, or if both are pointers.
    • Each call passes a dictionary as a hidden first argument. The compiler builds all dictionaries at compile time.
    • The dictionary holds the type arguments, derived types such as []T, sub-dictionaries, and entries for method calls on T.
    • In the recorded program, 16 type arguments gave 11 bodies and 16 dictionaries.

    Go compiles one body per GC shape. Types with the same underlying type share a body, and all pointers share one. A dictionary carries the real types.

    C

    The rules: constraints are type sets

    the Go specification, and the tests below
    constrainttype setthe body can use
    anyEvery typeAssignment, conversion to any, new, and a pointer to it. No operators.
    comparableTypes that support ==, also interface types== and != and a map key. Can panic with an interface argument.
    cmp.OrderedIntegers, floats, strings, and named types over them< <= > >= == !=, and + on all of them
    int | stringExactly int and stringOperators that all members share. MyInt is not a member.
    ~int | ~stringEvery type with underlying type int or stringThe same operators. MyInt is a member.
    interface{ String() string }Types with that methodThe method. A plain interface does this too.
    interface{ ~int; String() string }The intersection of both linesOperators and the method.

    An interface with a union or a ~ term is a constraint only. It cannot be the type of a variable.

    A constraint is an interface read as a set of types. The body can use only what every type in the set supports.

    D

    The rules: what the compiler refuses

    recorded from go build, Go 1.27.3
    you writethe compiler printsdo this
    Pass MyInt to T int | stringMyInt does not satisfy int | string (possibly missing ~ for int in int | string)Write ~int in the constraint.
    a + b with T anyinvalid operation: operator + not defined on a (variable of type T constrained by any)Use cmp.Ordered or a union.
    v.(type) with v of type Tcannot use type switch on type parameter value v (variable of type T constrained by any)Write any(v).(type), and ask if an interface fits better.
    New() where only the result uses Tin call to New, cannot infer TName it: New[int]().
    A method needs more than the type declaresT does not satisfy cmp.OrderedWrite a function with the stronger constraint.
    var x Number, where Number holds a unioncannot use type Number outside a type constraint: interface contains type constraintsUse it only in a type parameter list.
    Decode[T any]() in an interfaceinterface method must have no type parametersMake the interface generic, or use a function.
    A generic method for an interface methodcannot use Name{} (value of struct type Name) as Stringer value in variable declaration: Name does not implement Stringer (wrong type for method String)Add a method with no type parameters.

    I can name each refusal: a missing tilde, an operator that any lacks, a type switch on T, and an interface method with type parameters.

    E

    When not to use generics

    the simple form first
    situationusestatus
    A container: a set, a stack, a cacheType parameterApproved
    A slice or map algorithm with the same code for each typeType parameter, or the slices and maps packagesApproved
    The caller must get its own type backType parameterApproved
    The body only calls methodsInterfaceT adds nothing
    The behaviour differs per typeInterfaceT hides a switch
    One type exists todayPlain functionWait for the second
    The body needs reflection to workreflect, or code generationIf no constraint fits
    Decoding into a type the caller namesType parameterApproved
    two forms of one functiongo
    // Writer needs no type parameter: it uses a method and
    // nothing else, so an interface says the same thing.
    type Writer interface {
      Write(p []byte) (int, error)
    }
    
    // Greet is the plain version. Use this one.
    func Greet(w Writer) error {
      if _, err := w.Write([]byte("hello")); err != nil {
        return fmt.Errorf("greet: %w", err)
      }
      return nil
    }
    
    // GreetT adds a type parameter and removes nothing.
    func GreetT[W Writer](w W) error1 {
      if _, err := w.Write([]byte("hello")); err != nil {
        return fmt.Errorf("greet: %w", err)
      }
      return nil
    }
    1. 1The same body with a type parameter. It adds syntax and gives the caller nothing.

    I add a type parameter when two copies of the code differ only in a type. If the body only calls a method, I take an interface.

    F

    Type sets and inference

    tested
    numbergo
    // Number is a type set: int, int64, float64, and every
    // type whose underlying type is one of those.
    type Number interface {
      ~int | ~int64 | ~float641
    }
    
    // Sum keeps the named slice type S out of the result:
    // only the element type E comes back.
    func Sum[S ~[]E, E Number2](s S) E {
      var total E3
      for _, v := range s {
        total += v
      }
      return total
    }
    1. 1The tilde admits named types, such as a Celsius over float64.
    2. 2Constraint type inference: the caller writes Sum(temps), and E follows from S.
    3. 3The zero value of E. This works for every type in the set.

    S ~[]E takes a named slice type. Inference finds S from the argument, then finds E from the constraint on S.

    G

    Map and Filter

    tested
    mapfiltergo
    // Map applies f to each element.
    func Map[T, U any]1(in []T, f func(T) U) []U {
      out := make([]U, 0, len(in))
      for _, v := range in {
        out = append(out, f(v))
      }
      return out
    }
    
    // Filter keeps the elements that pass the test.
    func Filter[S ~[]T, T any](in S, keep func(T) bool2) S {
      var out S
      for _, v := range in {
        if keep(v) {
          out = append(out, v)
        }
      }
      return out
    }
    1. 1Two parameters: U comes from the function argument. Map(ids, strconv.Itoa) needs no brackets.
    2. 2Taking S returns the same named type that came in.

    A loop is often shorter. The slices package already has Sort, Index, Contains and many more.

    Filter returns S, not []T, so a named slice type survives the call.

    H

    A generic type

    tested
    setgo
    // Set is a defined type, so it can have methods.
    type Set[T comparable] map[T]struct{}1
    
    // Add puts v in the set. A map key is hashed here.
    func (s Set[T]) Add2(v T) { s[v] = struct{}{} }
    
    // Has reports whether v is in the set.
    func (s Set[T]) Has(v T) bool {
      _, ok := s[v]
      return ok
    }
    
    // SortedItems is a function, not a method, because it
    // needs a stronger constraint than Set declares.
    func SortedItems[T cmp.Ordered]3(s Set[T]) []T {
      return slices.Sorted(maps.Keys(s))
    }
    1. 1A defined type, so it can have methods. A map key needs comparable.
    2. 2The receiver repeats the parameter name, with no constraint.
    3. 3Set[T] accepts T here because cmp.Ordered types are comparable.

    A method cannot tighten the constraint of its type, so Sorted is a function with cmp.Ordered.

    I

    Two parameters and a mutex

    tested with -race
    cachego
    // Cache is safe for concurrent use.
    type Cache[K comparable, V any] struct {
      mu sync.Mutex
      m  map[K]V
    }
    
    // NewCache makes the map, so the zero value of Cache
    // is not used by accident.
    func NewCache[K comparable, V any]() *Cache[K, V]1 {
      return &Cache[K, V]{m: make(map[K]V)}
    }
    
    // Put stores v under k.
    func (c *Cache[K, V]) Put(k K, v V) {
      c.mu.Lock()
      defer c.mu.Unlock()
      c.m[k] = v
    }
    
    // Get returns the value, or the zero V and false.
    func (c *Cache[K, V]) Get(k K) (V, bool)2 {
      c.mu.Lock()
      defer c.mu.Unlock()
      v, ok := c.m[k]
      return v, ok
    }
    1. 1A constructor names the type arguments once: NewCache[int, string]().
    2. 2The miss returns the zero V, so the bool is the only reliable test.

    A generic store is one mutex and one map, with no conversions at the call site.

    J

    Generic methods

    since Go 1.27, tested
    optiongo
    // Option holds a value or nothing.
    type Option[T any] struct {
      v  T
      ok bool
    }
    
    // Some wraps a value.
    func Some[T any](v T) Option[T] { return Option[T]{v, true} }
    
    // None is the empty Option.
    func None[T any]() Option[T] { return Option[T]{} }
    
    // Get returns the value and whether it exists.
    func (o Option[T]) Get() (T, bool) { return o.v, o.ok }
    
    // Map has its own type parameter U. Before Go 1.27 this
    // had to be a function: Map(o, f), not o.Map(f).
    func (o Option[T]) Map[U any](f func(T) U) Option[U]1 {
      if !o.ok {
        return None[U]()2
      }
      return Some(f(o.v))
    }
    1. 1T comes from the receiver and U from this method. Each call site picks U, by inference or by name.
    2. 2The method returns a different instantiation of its own type.

    A generic method cannot implement an interface method. See the last two rows of panel D.

    Since Go 1.27, a method can declare its own type parameters. So Map chains on the value, and it does not need a package function.

    K

    A type at the call site

    since Go 1.27, tested
    clientgo
    // Client reads JSON documents by key.
    type Client struct {
      Docs map[string]string
    }
    
    // Get decodes the document into any type the caller
    // names. The type stays at the call site: c.Get[User].
    func (c *Client) Get[T any](key string) (T, error)1 {
      var v T
      doc, ok := c.Docs[key]
      if !ok {
        return v, fmt.Errorf("get %q: no such key", key)
      }
      if err := json.Unmarshal([]byte(doc), &v)2; err != nil {
        return v, fmt.Errorf("get %q: %w", key, err)
      }
      return v, nil
    }
    1. 1T appears only in the result, so the caller writes it: c.Get[User]("u1").
    2. 2A pointer to T: the decoder sees the real type through the interface value.

    A decoding client is the natural generic method: the caller names the type, and the client keeps its state.

    L

    Generic aliases

    since Go 1.24, tested
    aliasgo
    // Index is the same type as map[K][]V, not a new type.
    type Index[K comparable, V any] = map[K][]V1
    
    // Store is an old name for Cache. Old callers compile
    // while they move to the new name.
    type Store[K comparable, V any] = Cache[K, V]2
    1. 1The equals sign makes an alias. A plain map value needs no conversion.
    2. 2The migration case: old code keeps the old name, and both names are one type.

    A generic alias gives a type a second name, so I can move a generic type between packages and not break callers.

    M

    The pointer method pattern

    tested
    settergo
    // Setter says: P is *T, and *T has a Set method.
    type Setter[T any] interface {
      *T
      Set(string) error
    }
    
    // Parse needs both T, to allocate the slice, and P, to
    // call a pointer method on each element.
    func Parse[T any, P Setter[T]]2(in []string) ([]T, error) {
      out := make([]T, len(in))
      for i, s := range in {
        if err := P(&out[i]).Set(s)3; err != nil {
          return nil, fmt.Errorf("item %d: %w", i, err)
        }
      }
      return out, nil
    }
    1. 1A type set with one member: *T. So P can only be a pointer to T.
    2. 2The caller writes Parse[level](in). P follows from the constraint.
    3. 3Convert, then call. A plain T cannot call a pointer method.

    When T's methods have pointer receivers, I add a second parameter P that is constrained to *T, and call through it.

    N

    A constraint that names itself

    since Go 1.26, tested
    orderedgo
    // Lesser refers to itself in its own parameter list.
    // Go 1.26 lifted the rule that forbade this.
    type Lesser[T Lesser[T]] interface1 {
      Less(T) bool
    }
    
    // MinOf returns the smallest argument.
    func MinOf[T Lesser[T]](first T, rest ...T) T {
      low := first
      for _, v := range rest {
        if v.Less(low)2 {
          low = v
        }
      }
      return low
    }
    1. 1Go 1.25 refuses this line. The self-reference now compiles.
    2. 2A method call on T goes through the dictionary, so it does not inline.

    Since Go 1.26 a generic type can refer to itself in its own parameter list, so a constraint can name the type it constrains.

    O

    Compare with cmp

    tested
    comparego
    // Person is sorted by two fields.
    type Person struct {
      Name string
      Age  int
    }
    
    // ByAgeThenName sorts in place. cmp.Or returns the first
    // result that is not zero, so ties fall to the name.
    func ByAgeThenName(p []Person) {
      slices.SortFunc(p, func(a, b Person) int {
        return cmp.Or(1
          cmp.Compare(a.Age, b.Age)2,
          cmp.Compare(a.Name, b.Name),
        )
      })
    }
    1. 1Go 1.22. It returns the first argument that is not the zero value.
    2. 2Go 1.21. It returns -1, 0 or 1, and it orders NaN before every number.

    cmp.Compare gives a three-way result, and cmp.Or takes the first result that is not zero, so a multi-field sort is three lines.

    P

    See it: which code runs

    symbols from one build per type argument
    Describe[T], T =
    • Describe[go.shape.int]int, MyInt
    • Describe[go.shape.int64]int64
    • Describe[go.shape.float64]float64, Celsius
    • Describe[go.shape.string]string
    • Describe[go.shape.struct { X int }]A, B
    • Describe[go.shape.struct { S string }]C
    • Describe[go.shape.*uint8]*A, *B, *string
    • Describe[go.shape.[]int][]int
    • Describe[go.shape.[]main.MyInt][]MyInt
    • Describe[go.shape.interface {}]any
    • Describe[go.shape.interface { Error() string }]error

    Code: Describe[go.shape.int]

    Dictionary: .dict.Describe[main.MyInt]

    Shares this code with: int.

    16 type arguments, 11 compiled functions, 16 dictionaries.

    • The function is one line: it prints the type of its argument with %T. The compiler kept it out of line for this test.
    • int and int64 have the same size on this machine, but each has its own body.
    • any and error are both interfaces, but they have different bodies. An interface is never in a shape with a non-interface type.

    int and MyInt share a body. []int and []MyInt do not, because their underlying types differ.

    Q

    The cost, measured

    1,024 elements; runs interleaved
    workconcrete or genericinterfacewhat it shows
    Add an elementconcrete 0.29 ns; generic 0.29 ns1.56 nsOnce Sum inlines, a test finds the same opcodes as the concrete loop. Any gap here is noise. Interface elements need a dynamic call each.
    Call a method in a loopconcrete 1.21 ns; T value 1.35 ns; T pointer 1.35 ns1.35 nsA method on T uses the dictionary, so it is an indirect call like an interface call.
    Push and pop 1,024 ints2.4 µs; 0 allocations12.3 µs; 1,024 allocationsA []any boxes each of these ints. A []T stores the int directly.
    Sort 1,024 intsslices.Sort 24.0 µssort.Sort 55.9 µsThe comparison stays in line, so the generic sort is 2.3 times faster here.

    Go 1.27.3, 8-core Intel i9 laptop, GOMAXPROCS 16, median of 5 interleaved runs of 1 s, on a busy machine. Compare sizes, not small differences.

    Generic value code runs close to concrete code. A method call on T costs about the same as an interface call. The big gain is no boxing.

    R

    New in recent Go

    checked against each release's notes
    sincewhat changedwhat it means here
    1.18Type parameters, type sets, any, comparable, and inference.The start of generics.
    1.20Interface types satisfy comparable, even though a comparison can panic.Set[any] compiles. See panel A.
    1.21Packages slices, maps and cmp. Inference takes generic functions as arguments, considers methods, and handles mixed untyped constants.Map(ids, strconv.Itoa) and Max(1, 2.5) work.
    1.22cmp.Or. math/rand/v2 with a generic rand.N.Multi-field comparisons in one expression.
    1.24Generic type aliases are fully supported. Go 1.23 had a preview behind an experiment.Move a generic type and keep the old name.
    1.25The specification drops core types. No program changes.Old articles use a term that is gone.
    1.26A generic type can refer to itself in its type parameter list. errors.AsType is generic.Panel N. See G7 for AsType.
    1.27Methods can declare type parameters. Interface methods cannot, and a generic method cannot implement one. Function inference applies to every assignment and conversion. math/rand/v2 Rand has a generic method N.Panels J and K. The infer-assign drill question.
    S

    In the round

    45 minutes of build, 45 minutes of talk
    whenthe momentwhat to do or say
    buildYou start the store.Write a concrete map of your one entity. A generic store costs typing time and buys nothing with one type.
    buildYou need Sort, Index or Contains.Use the slices package. Do not write Map and Filter helpers.
    buildTwo handlers decode JSON in the same way.One small function with a type parameter is fine: T appears at the call site.
    talk"Why not an interface here?"An interface hides the type and boxes values. A type parameter keeps the type and stores values directly.
    talk"Why not generics here?"The body calls one method, so an interface says the same with less syntax.
    talk"How does Go compile this?"One body per GC shape, plus a dictionary per type argument. Name the cost from panel Q.
    talk"Does generic code cost more?"Arithmetic stays close to concrete code. A method call on T is indirect. Boxing is the cost that generics remove.

    I write the concrete type first. I generalize when the second type arrives, and I say so.

    T

    Drill

    each answer is the output of a real run

    0 of 9 known

    1. Predict the output.

      package main
      
      import "fmt"
      
      type MyInt int
      
      func Kind[T any](v T) string {
        switch any(v).(type) {
        case int:
          return "int"
        case string:
          return "string"
        }
        return "other"
      }
      
      func main() {
        fmt.Println(Kind(1))
        fmt.Println(Kind("a"))
        fmt.Println(Kind(MyInt(1)))
      }
    2. Predict the output. The second call has T = any.

      package main
      
      import "fmt"
      
      func IsZero[T comparable](v T) bool {
        var zero T
        return v == zero
      }
      
      func main() {
        var p *int
        var a any = p
        fmt.Println(IsZero(p))
        fmt.Println(IsZero(a))
        fmt.Println(IsZero[any](nil))
      }
    3. Predict the output.

      package main
      
      import (
        "cmp"
        "fmt"
      )
      
      func Max[T cmp.Ordered](a, b T) T {
        if a > b {
          return a
        }
        return b
      }
      
      func main() {
        x := Max(1, 2.5)
        fmt.Printf("%v %T\n", x, x)
        y := Max(1, 2)
        fmt.Printf("%v %T\n", y, y)
      }
    4. Predict the output.

      package main
      
      import "fmt"
      
      type Alias[T comparable] = map[T]bool
      
      type Defined[T comparable] map[T]bool
      
      func main() {
        a := Alias[string]{"x": true}
        d := Defined[string]{"x": true}
        fmt.Printf("%T\n", a)
        fmt.Printf("%T\n", d)
        _, ok := any(a).(map[string]bool)
        fmt.Println(ok)
        _, ok = any(d).(map[string]bool)
        fmt.Println(ok)
      }
    5. Predict the output.

      package main
      
      import "fmt"
      
      type MyInt int
      
      type Box[T any] struct{ V T }
      
      func Name[T any](v T) string { return fmt.Sprintf("%T", v) }
      
      func main() {
        fmt.Println(Name(1))
        fmt.Println(Name(MyInt(1)))
        fmt.Println(Name(Box[MyInt]{1}))
        var a any = Box[int]{1}
        _, ok := a.(Box[MyInt])
        fmt.Println(ok)
      }
    6. Predict the output.

      package main
      
      import (
        "cmp"
        "fmt"
        "math"
        "slices"
      )
      
      func main() {
        nan := math.NaN()
        fmt.Println(nan < 1, cmp.Less(nan, 1))
        fmt.Println(nan == nan, cmp.Compare(nan, nan))
        fmt.Println(min(nan, 1), slices.Min([]float64{1, nan}))
        s := []float64{2, nan, 1}
        slices.Sort(s)
        fmt.Println(s)
      }
    7. Predict the output. This needs Go 1.27.

      package main
      
      import (
        "fmt"
        "strconv"
      )
      
      type Box[T any] struct{ V T }
      
      func (b Box[T]) Map[U any](f func(T) U) Box[U] {
        return Box[U]{f(b.V)}
      }
      
      func main() {
        b := Box[int]{21}
        s := b.Map(func(n int) int { return n * 2 }).Map(strconv.Itoa)
        fmt.Printf("%T %q\n", s, s.V)
        f := Box[int].Map[string]
        fmt.Printf("%T\n", f)
      }
    8. Predict the output. This needs Go 1.27.

      package main
      
      import "fmt"
      
      func Twice[T any](v T) []T { return []T{v, v} }
      
      type Job struct {
        Run func(string) []string
      }
      
      func main() {
        var f func(int) []int = Twice
        j := Job{Run: Twice}
        list := []func(bool) []bool{Twice}
        g := (func(float64) []float64)(Twice)
        fmt.Println(f(1), j.Run("a"), list[0](true), g(1.5))
      }
    9. Predict the output.

      package main
      
      import "fmt"
      
      func Zero[T any]() T {
        var v T
        return v
      }
      
      func First[T any](s []T) T {
        if len(s) == 0 {
          return *new(T)
        }
        return s[0]
      }
      
      func main() {
        fmt.Printf("%q\n", Zero[string]())
        fmt.Println(Zero[*int]() == nil)
        fmt.Println(Zero[[2]int]())
        fmt.Println(First[int](nil))
        fmt.Println(Zero[error]() == nil)
      }
    U

    Numbers to say

    measured with testing.B
    shapes
    16 type arguments gave 11 bodies and 16 dictionaries.
    sum
    0.29 ns concrete and 0.29 ns generic, per element.
    method on T
    1.35 ns per call, against 1.35 ns for an interface.
    boxing
    []any is 5.2 times slower than []T, with 1,024 allocations against 0.
    sort
    slices.Sort is 2.3 times faster than sort.Sort.

    Go 1.27.3, 8-core Intel i9 laptop, on a busy machine. Use these as orders of magnitude.