From: Robert Griesemer Date: Wed, 9 Feb 2022 02:40:28 +0000 (-0800) Subject: spec: the type of a constant cannot be a type parameter X-Git-Tag: go1.18rc1~59 X-Git-Url: http://www.git.cypherpunks.su/?a=commitdiff_plain;h=20c300bc70e10071bb15091f37a8bb3464cf13e3;p=gostls13.git spec: the type of a constant cannot be a type parameter Add corresponding rules and a couple of examples. Fixes #50202. Change-Id: I4287b5e2d0fd29a0c871795e07f1bb529c9c6004 Reviewed-on: https://go-review.googlesource.com/c/go/+/384240 Trust: Robert Griesemer Reviewed-by: Ian Lance Taylor --- diff --git a/doc/go_spec.html b/doc/go_spec.html index a1800dcb5d..4d8312a917 100644 --- a/doc/go_spec.html +++ b/doc/go_spec.html @@ -1,6 +1,6 @@ @@ -679,6 +679,8 @@ or conversion, or implicitly when used in a operand in an expression. It is an error if the constant value cannot be represented as a value of the respective type. +If the type is a type parameter, the constant is converted into a non-constant +value of the type parameter.

@@ -2312,7 +2314,8 @@ ExpressionList = Expression { "," Expression } .

If the type is present, all constants take the type specified, and -the expressions must be assignable to that type. +the expressions must be assignable to that type, +which must not be a type parameter. If the type is omitted, the constants take the individual types of the corresponding expressions. If the expression values are untyped constants, @@ -5197,7 +5200,6 @@ as for non-constant x.

Converting a constant to a type that is not a type parameter yields a typed constant. -Converting a constant to a type parameter yields a non-constant value of that type.

@@ -5215,6 +5217,29 @@ int(1.2)                 // illegal: 1.2 cannot be represented as an int
 string(65.0)             // illegal: 65.0 is not an integer constant
 
+

+Converting a constant to a type parameter yields a non-constant value of that type, +with the value represented as a value of the type argument that the type parameter +is instantiated with. +For example, given the function: +

+ +
+func f[P ~float32|~float64]() {
+	… P(1.1) …
+}
+
+ +

+the conversion P(1.1) results in a non-constant value of type P +and the value 1.1 is represented as a float32 or a float64 +depending on the type argument for f. +Accordingly, if f is instantiated with a float32 type, +the numeric value of the expression P(1.1) + 1.2 will be computed +with the same precision as the corresponding non-constant float32 +addition. +

+

A non-constant value x can be converted to type T in any of these cases: