]> Cypherpunks repositories - gostls13.git/commitdiff
spec: document behavior of generic type switch cases
authorRobert Griesemer <gri@golang.org>
Wed, 9 Feb 2022 20:43:21 +0000 (12:43 -0800)
committerRobert Griesemer <gri@golang.org>
Wed, 9 Feb 2022 21:51:54 +0000 (21:51 +0000)
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>
doc/go_spec.html

index 4d8312a917298bc64dafcafeac45c19a13017d62..c0ed27730f04714f22831f348285528bdb88004e 100644 (file)
@@ -6253,6 +6253,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.