Go 1.18 generics
What you will learn from this topic
- A summary of the release note of go 1.18 generics with source code
- More example that didn't provide within official pages
How to install
Generics are not 100% generic
constraints
- Any
- Compareable
- Ordered
- Define with constraints package
<
less
<=
less or equal
>
greater
>=
greater or equal
e.g, interface are not Ordered but Compareable.
Reference: https://cs.opensource.google/go/x/exp/+/bbda1eaf:constraints/constraints.go
What can we do?
return max value
Insert multiple value into slice
BinarySearch
Sort
Can interface do the samething?
Yes, just a little uglier and more complicated
And not type safe
Insert multiple value into slice
Seems works?
Let's try to use this function like this
How about generic?
It can detect problem in compile time
binary search
Limitation
reference https://tip.golang.org/doc/go1.18#generics
- The Go compiler cannot currently handle type declarations inside generic functions or methods. We hope to provide support for this feature in Go 1.19.
- The Go compiler currently does not accept arguments of type parameter type with the predeclared functions real, imag, and complex. We hope to remove this restriction in Go 1.19.
I can't get it.
- The Go compiler currently only supports calling a method m on a value x of type parameter type P if m is explicitly declared by P's constraint interface. Similarly, method values x.m and method expressions P.m also are only supported if m is explicitly declared by P, even though m might be in the method set of P by virtue of the fact that all types in P implement m. We hope to remove this restriction in Go 1.19.
- Embedding a type parameter, or a pointer to a type parameter, as an unnamed field in a struct type is not permitted. Similarly, embedding a type parameter in an interface type is not permitted. Whether these will ever be permitted is unclear at present.
- A union element with more than one term may not contain an interface type with a non-empty method set. Whether this will ever be permitted is unclear at present.
This doesn't work