Go team released Go 1.18 Beta 1 in December 2021, introducing support for generic programming using type parameters, a much-anticipated feature.
Note: If you prefer, you can use the Go playground in “Go dev branch” mode to try new features with generics.
What is new in generics?
Type parameter lists look like ordinary parameter lists with square brackets. It is customary to start type parameters with upper-case letters to emphasize that they are types.
Let’s take a look at the function
If we want this function to work with other number types such as
float64, we need to declare a new function to handle the new type. To solve that problem, we use generics. The type parameter
T, declared in a type parameter list, takes the place of
Type parameter lists also have a type for each type parameter. This type defines a set of types. It is called the type constraint. In Go, type constraints must be interfaces.
Let’s take a look at the example below.
constraints.Ordered is a type constraint.
Ordered defines the set of all integer, floating-point, and string types.
~T means the set of all types with the underlying type
Check this discussion for more information.
When declaring a variable without specifying an explicit type (either by using the
:= syntax or
var = expression syntax), the variable’s type is inferred from the value on the right-hand side.
You can call the
min function without type inference. Sometimes, passing type arguments lead to more verbose code.