Go Generics Lead Designer Introduces the Best Time to Use Generics

A recent article on the topic of  Go Generics causing code to run slower has generated a lot of discussion. Because Go developers have been looking forward to the "generics" feature for a long time, but finally found that there is a gap.

Ian Lance Taylor, the main designer of Go generics, also noticed the relevant discussions, so he recently published his 2021 speech on the Go official blog - " When To Use Generics " to introduce the best time to use Go generics.

The article mentioned above points out that historically, systems languages ​​such as C++, D, and even Rust have adopted a monomorphic approach to generics. However, the generic implementation of Go 1.18 does not rely entirely on Monomorphization, but instead employs a partial monomorphization technique known as "GCShape stenciling with Dictionaries". The benefit of this approach is that it can greatly reduce the amount of code, but in certain cases, it will lead to slower code.

According to Ian Lance Taylor, Go's general development guidelines dictate that developers should write Go programs by writing code, not defining types. When it comes to generics, if you write your program by defining type parameter constraints, you're on the wrong track in the first place. The correct solution should be to start by writing a function. When the role of type parameters is clear, it is easy to add type parameters.

Next, Ian lists 4 situations where type parameters can be useful:

  1. Use language-defined special container types
  2. general data structure
  3. The case where the type parameter is preferably a function, not a method
  4. Different types need to implement common methods

At the same time, it also reminds that it is not suitable to use type parameters:

  1. Do not replace interface types with type parameters (Interface Type)
  2. Don't use type parameters if the method implementation is different
  3. Use reflection where appropriate

Finally, Ian gives a brief guideline on the use of generics, when developers find themselves writing the exact same code multiple times, and the only difference between those copies is the use of different types, then type parameters can be considered. In other words, developers should avoid using type parameters until they find themselves writing the exact same code multiple times.

Further reading: The father of the Go language introduces generics

Guess you like

Origin www.oschina.net/news/191309/when-generics