Type parameters
Function can be written to work with multiple types using type parameters.
This declaration means that s
is a slice of any type T
that fulfills the built-in constraint comparable
. x
is also a value of the same type.
Constraints
Go uses constraint-based approach for generics.
Constraints are used to create a union of allowed types:
There’s a built-in constraint type comparable
. At the moment I didn’t find any info on other types. I’ll add them later here.
Built-in constraint types:
comparable
- allows == and != operationsany
Generic types
Go also supports generic types: