When to Use Generics in Go?


  • First, it increases boilerplate code. Indeed, whenever we want to add a case, it will require duplicating the range loop.
  • Meanwhile, the function now accepts an empty interface, which means we are losing some of the benefits of Go being a typed language. Indeed, checking whether a type is supported is done at runtime instead of compile-time. Hence, we also need to return an error if the provided type is unknown.
  • Last but not least, as the key type can be either int or string, we are obliged to return a slice of empty interfaces to factor out key types. This approach increases the effort on the caller-side as the client may also have to perform a type check of the keys or extra conversion.
  • A set of behaviors (methods)
  • But also arbitrary type
./main.go:29:15: methods cannot have type parameters

Common uses and misuses

  • Data structures. For example, we can use generics to factor out the element type if we implement a binary tree, a linked list, or a heap.
  • Functions working with slices, maps, and channels of any type. For example, a function to merge two channels would work with any channel type. Hence, we could use type parameters to factor out the channel type:
  • Meanwhile, instead of factoring out a type, we can factor out behaviors. For example, the sort package contains functions to sort different slice types such as sort.Ints or sort.Float64s. Using type parameters, we can factor out the sorting behaviors that rely on three methods, Len, Less, and Swap:
  • When just calling a method of the type argument. For example, consider a function that receives an io.Writer and call the Write method:
In this case, using generics wouldn’t bring any value whatsoever, and we should make the w argument an io.Writer directly:
  • When it makes our code more complex. Generics are never mandatory, and as Go developers, we have been able to live without them for more than a decade. If writing generic functions or structures we figure out that it doesn’t make our code clearer, we should probably reconsider our decision for this particular use case.




Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Teiva Harsanyi

Teiva Harsanyi


Software Engineer @Docker 🐳 | 📖 100 Go Mistakes author | 改善