Some programming languages such as C++ and Rust support generic specialization, does Go generic support it?
Specialization is an extension of the generic function code. For example, for a generic function, its implementation is the same for all types (type sets) that satisfy the generic argument. If we want to do a special implementation of the function for one of these type sets, some languages that support generic specialization can support it, such as C++ template:
Here fun
is a function template, but there is a special implementation of this function for the int
type.
Rust also has a similar function:
|
|
Here MyTrait
has a default implementation for the generic type T
, but has a specific implementation for the specific type Special
.
Other programming languages do not currently support specialization, but can implement similar functionality through method overloading, such as typescript, C#, etc. In addition, complex specialization includes partial specialization features.
So the question is, do Go’s generics (type parameters) support specialization? Let’s write an example:
Here we define a generic type List[T any]
, including its generic method Len() int
, and then we try to define a “specialization” method Length() int
.
Compile it, no problem, the program compiles normally, does the Go generic really support specialization?
Let’s try adding another special generalization method:
Try compiling again at this time, the compilation error:
|
|
In fact, the error message already tells us that int
is not a built-in integer type, but the name of a type parameter, equivalent to our common T
, K
, V
. It is confusing to use int
as the name of a type parameter here.
So the answer is clear, Go 1.18 does not support generic specialization , so be careful not to fall into the hole.