From 41d6687084f1837311021a134968479cb40f9021 Mon Sep 17 00:00:00 2001 From: Robert Griesemer Date: Mon, 22 Jan 2024 15:46:01 -0800 Subject: [PATCH] spec: clarify iteration variable type for range over integer Also: report language version (plus date) in spec header. Fixes #65137. Change-Id: I4f1d220d5922c40a36264df2d0a7bb7cd0756bac Reviewed-on: https://go-review.googlesource.com/c/go/+/557596 TryBot-Bypass: Robert Griesemer Reviewed-by: Matthew Dempsky Reviewed-by: Robert Griesemer --- doc/go_spec.html | 38 +++++++++++++++++++++++++------------- 1 file changed, 25 insertions(+), 13 deletions(-) diff --git a/doc/go_spec.html b/doc/go_spec.html index bd974b3c489..42300750bc3 100644 --- a/doc/go_spec.html +++ b/doc/go_spec.html @@ -1,6 +1,6 @@ @@ -6661,7 +6661,7 @@ array or slice a [n]E, *[n]E, or []E index i int a[i] E string s string type index i int see below rune map m map[K]V key k K m[k] V channel c chan E, <-chan E element e E -integer n integer type I value i I +integer n integer type value i see below
    @@ -6703,26 +6703,33 @@ is nil, the range expression blocks forever.
  1. For an integer value n, the iteration values 0 through n-1 -are produced in increasing order, with the same type as n. +are produced in increasing order. If n <= 0, the loop does not run any iterations.
-

-The iteration values are assigned to the respective -iteration variables as in an assignment statement. -

-

The iteration variables may be declared by the "range" clause using a form of short variable declaration (:=). -In this case their types are set to the types of the respective iteration values -and their scope is the block of the "for" statement; -each iteration has its own separate variables [Go 1.22] +In this case their scope is the block of the "for" statement +and each iteration has its own new variables [Go 1.22] (see also "for" statements with a ForClause). -If the iteration variables are declared outside the “for” statement, -after execution their values will be those of the last iteration. +If the range expression is a (possibly untyped) integer expression n, +the variable has the same type as if it was +declared with initialization +expression n. +Otherwise, the variables have the types of their respective iteration values. +

+ +

+If the iteration variables are not explicitly declared by the "range" clause, +they must be preexisting. +In this case, the iteration values are assigned to the respective variables +as in an assignment statement. +If the range expression is a (possibly untyped) integer expression n, +n too must be assignable to the iteration variable; +if there is no iteration variable, n must be assignable to int.

@@ -6765,6 +6772,11 @@ for i := range 10 {
 	// type of i is int (default type for untyped constant 10)
 	f(i)
 }
+
+// invalid: 256 cannot be assigned to uint8
+var u uint8
+for u = range 256 {
+}