diff options
author | Robert Griesemer <gri@golang.org> | 2022-02-09 12:43:21 -0800 |
---|---|---|
committer | Robert Griesemer <gri@golang.org> | 2022-02-09 21:51:54 +0000 |
commit | 9867262dfd9b1ba2f212c24dbf26758f81d7cd58 (patch) | |
tree | 3da90b6b1b83ff0eb75a463f86f3ba73785f5afc /doc | |
parent | 20c300bc70e10071bb15091f37a8bb3464cf13e3 (diff) | |
download | go-9867262dfd9b1ba2f212c24dbf26758f81d7cd58.tar.gz go-9867262dfd9b1ba2f212c24dbf26758f81d7cd58.zip |
spec: document behavior of generic type switch cases
Fixes #51110.
Change-Id: I11370417f1ef435b05dfab18eeabc2c3c1b7b8a1
Reviewed-on: https://go-review.googlesource.com/c/go/+/384674
Trust: Robert Griesemer <gri@golang.org>
Trust: Dan Scales <danscales@google.com>
Reviewed-by: Dan Scales <danscales@google.com>
Reviewed-by: Ian Lance Taylor <iant@golang.org>
Diffstat (limited to 'doc')
-rw-r--r-- | doc/go_spec.html | 26 |
1 files changed, 26 insertions, 0 deletions
diff --git a/doc/go_spec.html b/doc/go_spec.html index 4d8312a9172..c0ed27730f0 100644 --- a/doc/go_spec.html +++ b/doc/go_spec.html @@ -6254,6 +6254,32 @@ if v == nil { </pre> <p> +A <a href="#Type_parameters">type parameter</a> or a <a href="#Type_declarations">parameterized type</a> +may be used as a type in a case. If upon <a href="#Instantiations">instantiation</a> that type turns +out to duplicate another entry in the switch, the first matching case is chosen. +</p> + +<pre> +func f[P any](x any) int { + switch x.(type) { + case P: + return 0 + case string: + return 1 + case []P: + return 2 + case []byte: + return 3 + default: + return 4 + } +} + +var v1 = f[string]("foo") // v1 == 0 +var v2 = f[byte]([]byte{}) // v2 == 2 +</pre> + +<p> The type switch guard may be preceded by a simple statement, which executes before the guard is evaluated. </p> |