Go 2 generics in 5 minutes

Alberto de Murga
5 min readFeb 5, 2021
Two generic gophers
Two generic gophers. Photo by Lukáš Vaňátko on Unsplash

The inclusion or not of generics in the Go language has been a long-standing discussion and cause of drama since the first appearance of the language in 2009. Rivers of ink have been poured in long discussions about if generics are good or bad, and if the language needs to support them or not. Up to this moment, the Go team has decided to leave generics outside the language.

However, with the announcement of the second version of the language, the Go team opened the discussion to add generics to the language. There have been different drafts about how to add generics finally settling down in what it seems a final design draft.

Generics in bullet points

The draft is quite long but not as dense as it could have been expected for such a document. It is important to highlight that the objective of the Go team is to create a backwards compatible design which addresses people’s needs for generics without making the language more complex than necessary.

The specification can be summarised in the following bullet points, that we will develop after. However, it is advisable for anyone interested in the topic to read the full document linked at the bottom of the article. We are assuming that the reader is familiar with basic Go concepts like functions, types, and interfaces.

  • Functions and types can have an additional type parameter list in front of the normal ones using square brackets to indicate the generic types used. These type parameters can be used like any other parameter in the rest of the definition and body.
  • The type parameters are defined using constraints, that are interface types. Constraints define the methods required and types permitted for the type argument and describe the methods and operations available for the generic type.
  • We can use type inference which will often permit omitting type arguments.
  • We have a special constraint named any which behaves similarly to interface{}, and a new package named constraints which will have commonly used constraints.

Defining and using generic functions

Functions can take an extra list of parameters surrounded by brackets instead of parenthesis, and they can be

Alberto de Murga

Software engineer at @bookingcom. I like to make things, and write about what I learn. I am interested in Linux, git, JavaScript and Go, in no particular order.