A recent article on the topic of Go Generics slow down code has been widely discussed. This is because Go developers have been waiting for a feature called “generics” for a long time, but in the end they found it to be a bit of a letdown.
Ian Lance Taylor, the lead designer of Go generics, has also noticed the discussion, so he recently published his 2021 talk on the official Go blog, “When To Use Generics,” to introduce the best time to use Go generics.
The article mentioned above points out that historically, system languages such as C++, D, and even Rust have used the monomorphization method to implement generics. However, Go 1.18’s implementation of generics does not rely exclusively on monomorphization, but instead uses a partial monomorphization technique called “GCShape stenciling with Dictionaries”. This approach has the advantage of significantly reducing the amount of code, but in certain cases, it can lead to slower code.
Ian Lance Taylor says that Go’s general development guidelines require that developers write Go programs by writing code, not by defining types. When it comes to generics, if you write a program by defining type parameter constraints, you’re starting off on the wrong foot. The correct solution is to start by writing functions, and once the role of type parameters is clear, it’s easy to add them.
Ian then lists four situations in which type parameters can be effective。
- special container types defined using the language
- generic data structures
- when the preferred type parameter is a function, not a method
- different types need to implement generic methods
It also reminds that the use of type parameters is not appropriate in the following cases.
- do not use type parameters instead of interface types (Interface Type)
- do not use type parameters if the method implementation is different
- use reflection (reflection) where appropriate
Finally, Ian gives a brief guideline for the use of generic types. When developers find themselves writing the exact same code multiple times, and the only difference between these copies is the use of different types, then they can consider using type parameters. In other words, developers should avoid using type parameters until they find themselves writing the exact same code multiple times.
Extended reading: Father of Go Language Introduces Generics