Skip to content

Instantly share code, notes, and snippets.

@paulsmith
Created December 21, 2021 17:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save paulsmith/5424cdf4a3d9764c952d6e03990e6059 to your computer and use it in GitHub Desktop.
Save paulsmith/5424cdf4a3d9764c952d6e03990e6059 to your computer and use it in GitHub Desktop.
When to use generics in Go

When to use generics

aka generic guidelines

It's late 2021, and Go is about to add "generics" (i.e., type parameters for types and functions) to upcoming release version 1.18.

Here is some guidance for Go programmers, cribbed from a talk by Ian Lance Taylor.

First, write Go programs by writing code, not by defining types.

In other words, you might not need generics.

When it comes to generics, if you start writing your program by defining new type parameter constraints, you're probably on the wrong path.

Start by writing functions. It's easy to add type parameters later, when it's clear that they'll be useful.

When are type parameters useful?

  • Functions that work on slices, maps, and channels of any element type
  • General purpose data structures (eg., linked list, binary tree)
    • When operating on type parameters, prefer functions to methods
  • When a method looks the same for all types

When are type parameters not useful?

  • When just calling a method on the type argument (use an interface type)
  • When the implementation of a common method is different for each type
  • When the operation is different for each type, even without a method (use reflection)

One simple guideline:

Avoid boilerplate: if you find yourself writing the exact same code multiple times, where the only difference between the copies is that the code uses different types, consider whether you can use a type parameter.

Corollary: don't use type parameters prematurely, wait until you are about to write boilerplate code.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment