Skip to content

spec: range over integer expressions underspecified #65137

@griesemer

Description

@griesemer

The following code

var u uint8
for u = range 258 {
   println(u)
}

prints the values 0, 1, 2, ... 255, 0, 1; that is the integer "wraps around". This seems incorrect, but the spec is silent on the subject.

I believe the rules need to be extended such that if:
a) the iteration variable is already declared (u in the example above):

  • the iteration expressions must be assignable to the iteration variable (if the expression is a constant, it must fit into the iteration variable)

b) the iteration variable is being declared (as in for u := range x):

  • if the iteration expression is typed, the iteration variable has the same type
  • if the iteration expression is an untyped constant, it is given the type int, the constant must be representable as an int, and the iteration variable will be of type int

I believe these rules follow more or less from the existing prose (assignment to the iteration variables happens as in an assignment statement), but the fact that the compiler and type checkers get this wrong is an indication that we need more precise prose or better examples.

We need to pin this down before the 1.22 release otherwise we may not be able to make these changes anymore in a backward-compatible way.

cc: @rsc

Metadata

Metadata

Assignees

Labels

Type

No type

Projects

Status

Done

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions