Introduction video: https://youtu.be/Pa_e9EeCdy8?si=IvEhP5dFZWIyYljs
The summary is as below:
Type Constraint
Specifying type constraint after the type parameter T.
1 | func min[T constraints.Ordered] (x,y T) T |
The type constraints are interfaces, for example the existing ordered constraints: https://pkg.go.dev/golang.org/x/exp/constraints#Ordered
Define your own type constraint:
1 | // Integer is another type constraint interface |
The ~string
means any type that uses string as underlying type, for example:
1 | type Line string |
Type Constraint Literal
1 | // it is common to write type constraint literal "in line". |
Struct with Generic
This is an example about how to define generic struct:
1 | // a generic binary tree, can be Treep[T any ] |
Type Inference
The type argument float64 can be inferred from the arguments a and b:
1 | func min[T constraints.Ordered](x, y T) T |
Example about Complex Type Inference
1 | type Point []int32 |
When to Use Generics
Please also use your own judgement:
- Functions that work on slices, maps and channels of any element type.
- General purpose data structures.
- When operating on type parameters, prefer functions over methods.
- When a method looks the same for all types.