From 9867262dfd9b1ba2f212c24dbf26758f81d7cd58 Mon Sep 17 00:00:00 2001 From: Robert Griesemer Date: Wed, 9 Feb 2022 12:43:21 -0800 Subject: [PATCH] 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 Trust: Dan Scales Reviewed-by: Dan Scales Reviewed-by: Ian Lance Taylor --- doc/go_spec.html | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) diff --git a/doc/go_spec.html b/doc/go_spec.html index 4d8312a917..c0ed27730f 100644 --- a/doc/go_spec.html +++ b/doc/go_spec.html @@ -6253,6 +6253,32 @@ if v == nil { } +

+A type parameter or a parameterized type +may be used as a type in a case. If upon instantiation that type turns +out to duplicate another entry in the switch, the first matching case is chosen. +

+ +
+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
+
+

The type switch guard may be preceded by a simple statement, which executes before the guard is evaluated. -- 2.50.0