From 0c53fd590e8a5885ce9ee4045c06119e48660b25 Mon Sep 17 00:00:00 2001 From: Paul Duncan Date: Wed, 19 Jan 2022 18:00:21 -0500 Subject: content/posts/2022-01-17-generics-in-go-1.18.md: wording fixes, add info about tilde prefixes --- content/posts/2022-01-17-generics-in-go-1.18.md | 27 +++++++++++++++++-------- 1 file changed, 19 insertions(+), 8 deletions(-) (limited to 'content/posts') diff --git a/content/posts/2022-01-17-generics-in-go-1.18.md b/content/posts/2022-01-17-generics-in-go-1.18.md index 5379ab7..1a44b03 100644 --- a/content/posts/2022-01-17-generics-in-go-1.18.md +++ b/content/posts/2022-01-17-generics-in-go-1.18.md @@ -81,7 +81,7 @@ package main import "fmt" // Return sum of all numeric values in slice. -func Sum[V int|float32|complex64](vals []V) V { +func Sum[V ~int|~float32|~complex64](vals []V) V { var r V for _, v := range(vals) { @@ -133,7 +133,7 @@ package main import "fmt" // Fraction -type Frac[T int|int32|int64] struct { +type Frac[T ~int|~int32|~int64] struct { num T // numerator den T // denominator } @@ -174,14 +174,22 @@ func main() { ```   -Interface type declarations can now be used to specify type unions. For -example, the `Frac` type declaration from the previous example could be -written like this instead: +Interface type declarations can now be used to define the constraints +that a matching type must satisfy. In addition to the ability to +specify methods that a matching type must implement, a type constraint +specified as an interface may also specify a union of terms indicating +the set of matching types. + +Type union terms can be tilde-prefixed (example: `~int`), which +indicates that the *underlying type* must match the given type. + +For example, the `Frac` type declaration from the previous example could +be written like this instead: ```go // Integral number type. type integral interface { - int | int32 | int64 + ~int | ~int32 | ~int64 } // Fraction @@ -192,9 +200,9 @@ type Frac[T integral] struct { ```   -There are two new keywords: +There are two new predeclared identifiers: -* `any`: Alias for `interface {}`. +* `any`: An alias for `interface {}`. * `comparable`: Any type which can be compared for equality with `==` and `!=`. Useful for the parameterizing map keys. @@ -298,6 +306,9 @@ Other useful tidbits: need to rewrite your existing code. * There are [two new tutorials][] which explain generics and fuzzing. +**Update (2021-01-19):** Minor wording changes, add information about +tilde prefixes in type constraints. + [go]: https://go.dev/ "Go programming language" [go 1.18]: https://tip.golang.org/doc/go1.18 -- cgit v1.2.3