Skip to content
Tutorials Center
My learning

Topics

Lesson 58 of 147 ยท Generics

Generics in Practice: When to Use Them

Learn when Go generics are the right tool and when interfaces or plain code are better - algorithms vs containers, performance, common mistakes and the slices and maps packages.

You now know the syntax of generic functions, constraints and generic types. The harder question is the practical one: should you reach for a type parameter? Go's designers added generics reluctantly, and the community's advice has settled into a simple rule: write ordinary code first, and add type parameters when you notice you are writing the same code for different types.

This lesson gives you a way to decide. We look at the places where generics clearly win (algorithms and containers), the places where an interface is the better answer, what generics cost at run time, and the mistakes that beginners make most often. Along the way you will see why the slices and maps packages are the best model of good generic code.

Where generics shine

Generics earn their keep in two situations.

1. Algorithms that work on any element type. Searching, sorting, reversing, filtering, grouping, deduplicating: none of these care what the elements are, only that they can be compared or copied. Before generics you wrote them per type or gave up type safety with any.

2. Containers that hold values of one type. A stack, queue, set, ordered map, cache or linked list is a data structure whose logic is identical for every element type. Generic types let you write it once and keep full type safety for the caller.

Here is a small toolbox of the first kind. Notice that every function says exactly what it needs from T and nothing more:

Go Three small generic algorithms

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

Each constraint is as loose as it can be: Reverse accepts any because it only moves values around, Unique needs comparable for the map key, and MaxBy needs cmp.Ordered only for the key, not for the element. Accepting a key function instead of requiring T to be ordered is a common trick that makes an algorithm usable with types you do not control.

A good test: can you describe the function without naming a concrete type? "Reverses a slice", "keeps the first of each value", "finds the element with the biggest key". If so, it probably wants a type parameter.

When an interface is the better tool

A type parameter is for code that works with one type at a time, chosen by the caller. An interface is for code that works with several different types at once, or that only needs to call methods. If the body of your function only calls methods on its argument, a plain interface parameter is simpler and usually equivalent:

Go Generic or interface: same result, simpler code

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

The last part is the key difference. A []T holds values of exactly one type, so you cannot put a Rect and a Circle in the same []T. To store different concrete types side by side you need an interface type. That is runtime polymorphism, and generics do not replace it.

A classic stumbling block: slices of concrete types

Go slices are not covariant. A []Circle is not a []Shape, even though Circle implements Shape, because the two have different memory layouts (a circle value versus an interface value holding a circle). This trips up almost everyone once:

Go A []Circle is not a []Shape (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

The compiler says:

TEXT
./main.go:21:20: cannot use circles (variable of type []Circle) as []Shape value in argument to total

This is one of the few places where a type parameter genuinely helps, because it lets one function accept a slice of any single shape type without copying it into a []Shape first:

Go A type parameter accepts any slice of shapes

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

What generics cannot express

Go's generics are deliberately small. Three limits matter in practice.

Methods with their own type parameters have limits. A generic type can have methods that use the type's parameters, as in func (s *Stack[T]) Push(v T). Since Go 1.27, a method may also declare an extra type parameter of its own. Earlier versions rejected this with method must have no type parameters, so you may see the old advice online. The extra parameter makes chains like this possible:

Go A method with its own type parameter (Go 1.27)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

There is still a catch: a method with type parameters cannot be part of an interface, because an interface method set must be fixed when the program is compiled. Declaring one is an error:

Go Interface methods cannot have type parameters (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

TEXT
./main.go:12:5: interface method must have no type parameters
./main.go:12:25: undefined: U

A concrete interface such as Map(f func(int) string) Box[string] is also not satisfied by Box[int], since its method has a different, generic signature. Use ordinary functions (func MapBox[T, U any](b Box[T], f func(T) U) Box[U]) when you need something to cross an interface, and remember that slices and iter favor functions over chained methods.

You cannot use operators the constraint does not allow. With any you can assign and pass values around, but not compare them:

Go Comparing values of type any-constrained T (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

TEXT
./main.go:7:6: invalid operation: it == target (incomparable types in type set)

Change the constraint to comparable and it compiles. The compiler checks the generic body once, against the constraint, so a function can never fail later for some unlucky type argument.

There are no generic variadic type lists, no specialization and no operator overloading. You cannot write one version for int and a faster one for string and let the compiler choose. If you need different behaviour per type, that is an interface method, not a type parameter.

Common mistakes

Switching on the type parameter

If you find yourself writing a type switch on a value of type T, you have probably re-invented an interface the hard way:

Go A type switch inside a generic function is a smell

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

The first version compiles for 3.5 but quietly returns "unknown". The second makes the requirement part of the type system, so passing something without a Describe method is a compile error.

Adding type parameters "just in case"

func Process[T any](v T) T that merely returns its argument is pointless, and func Save[T any](x T) error that wraps json.Marshal(x) gains nothing over func Save(x any) error. A type parameter earns its place only if it links two or more places in the signature (the argument and the result, or an element type and a function over it), or if the body needs T itself (var zero T, make([]T, n), a map key). If T appears once in the parameter list and nowhere else, replace it with the plain type.

Over-constraining

Do not demand more than the body uses. [T int | float64] for a function that only moves values around rejects int32 for no reason, and [T cmp.Ordered] where only == is needed rules out structs. Use the weakest constraint that lets the body compile.

Generic types where a concrete one is enough

A Server[T any] where T is always Config is just noise. Wait until a second instantiation actually exists. Generics are easy to add later, because call sites with inferred arguments usually do not change.

Performance: what the compiler does

Go does not copy the function body for every type argument the way C++ templates do, and it does not box values the way Java generics do. It uses a hybrid called GC shape stenciling with dictionaries:

  • Type arguments with the same GC shape (essentially the same memory layout) share one compiled version of the function. All pointer types, for example, share one shape.
  • Operations that differ between types in a shape (calling a method, converting to an interface) look up the right implementation through a hidden dictionary passed with each call.

The practical effect is that generic code is usually as fast as hand-written code for built-in types, can be a little slower than a hand-specialized version when it must go through the dictionary (especially method calls on pointer-shaped type arguments, which can block inlining), and avoids the allocations that any causes. You can see the allocation difference without a benchmark runner, using testing.AllocsPerRun:

Go Generic sum versus boxing into []any

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

The generic version allocates nothing, because []int is passed as is. Storing 1,000 ints in a []any allocates for (almost) every element, because each int that does not fit Go's small-value cache must be copied to the heap behind an interface.

Do not choose generics or interfaces for speed alone. A method call through an interface and one through a generic dictionary both cost a few nanoseconds. Pick the clearer design, and measure with a benchmark (see Benchmarks and Fuzzing) only if profiling shows a hot spot.

Learning from the standard library

The best examples of restrained generic design are the slices, maps and cmp packages, added in Go 1.21. Look at what they do and what they leave out:

Go The standard library as a model

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

Three design habits are worth copying. The functions take slices and maps, not custom container types, so they work with whatever data you already have. Constraints are minimal (cmp.Ordered, comparable). And where an element type is not ordered, the function takes a comparison function (SortFunc, BinarySearchFunc) instead of demanding a method. The package also leaves out Map and Filter on purpose; the iterator functions in the next lessons cover them.

A checklist before you add a type parameter

  1. Is the logic identical for every type, apart from the type itself? If not, use an interface.
  2. Do I need the concrete type in the result or in a second parameter? If not, an interface or any may do.
  3. Is there a standard-library function (slices, maps, cmp, iter) that already does this?
  4. Can I describe what I need from T with one small constraint?
  5. Do I have two real call sites with different types today?

If you answered "yes" to 1, 4 and 5, write the generic version.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. A function only calls Area() and Name() on its argument. What is usually the simplest design?

    When the body only calls methods, an interface parameter does the same job with less syntax. Use a type parameter when you need the concrete type itself, for example for slices of one type or for returning the same type.
  2. 2. Why does total(circles) fail when circles is a []Circle and total takes a []Shape?

    Go slices are not covariant. []Circle and []Shape have different element types and layouts, so one is never assignable to the other. A generic Total[S Shape](s []S) accepts both.
  3. 3. Which of these is NOT allowed in Go 1.27?

    Since Go 1.27 a concrete method can declare its own type parameter, but an interface method cannot: the compiler reports 'interface method must have no type parameters'.
  4. 4. What does func Index[T any](items []T, x T) int fail to do when its body uses ==?

    The body is checked against the constraint. any does not guarantee that == is valid, so you need comparable.
  5. 5. What is a good sign that a type switch inside a generic function should be redesigned?

    Switching on the dynamic type of a type-parameter value means the behaviour depends on the type, which is exactly what interface methods are for.

Summary

  • Generics are best for algorithms that ignore element details and for containers that hold one element type; start with plain code and generalize when you repeat yourself.
  • If the body only calls methods, use an interface. Use a type parameter when you need the concrete type: slices of one type, results that match the input, var zero T, map keys.
  • A []Circle is not a []Shape; func Total[S Shape](s []S) accepts both.
  • Methods may have their own type parameters since Go 1.27, but interface methods may not; any does not allow ==; and there is no specialization.
  • Avoid type switches on type parameters, unnecessary type parameters and over-tight constraints.
  • Go compiles generics with GC shape stenciling and dictionaries: fast for built-in types and free of the boxing allocations of []any.
  • Copy the style of slices, maps and cmp: minimal constraints and comparison functions.

Next: Iterators: range over Functions shows how Go 1.23 lets for range work over custom sequences.