aboutsummaryrefslogtreecommitdiff
path: root/content/posts
diff options
context:
space:
mode:
authorPaul Duncan <pabs@pablotron.org>2022-01-19 18:00:21 -0500
committerPaul Duncan <pabs@pablotron.org>2022-01-19 18:00:21 -0500
commit0c53fd590e8a5885ce9ee4045c06119e48660b25 (patch)
tree569321058c4da40450a631356a70c02d3b22f6b1 /content/posts
parent99da12a40cf8e3d22057523f0c2f4ef7532cc20a (diff)
downloadpablotron.org-0c53fd590e8a5885ce9ee4045c06119e48660b25.tar.bz2
pablotron.org-0c53fd590e8a5885ce9ee4045c06119e48660b25.zip
content/posts/2022-01-17-generics-in-go-1.18.md: wording fixes, add info about tilde prefixes
Diffstat (limited to 'content/posts')
-rw-r--r--content/posts/2022-01-17-generics-in-go-1.18.md27
1 files changed, 19 insertions, 8 deletions
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() {
```
&nbsp;
-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 {
```
&nbsp;
-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