ARTICLE AD BOX
Go v1.22 added the ability to easily range from 0 to n-1:
// Prints 0, 1, 2 on separate lines. for i := range 3 { fmt.Println(i) }However, it doesn't work as expected when the expression's type is a type parameter constrained to be an integer type (playground):
func foo[Int constraints.Integer](n Int) { // error: cannot range over n (variable of type Int constrained by constraints.Integer): int and int8 have different underlying types for i := range n { fmt.Println(i) } }Why isn't this supported? I don't see anything in the specification for for statements with a range clause that suggest a conflict between the iteration variable type and the iteration value type (emphasis added):
For an integer value n, where n is of integer type or an untyped integer constant, the iteration values 0 through n-1 are produced in increasing order. If n is of integer type, the iteration values have that same type. [...]In this case, n is of integer type Int, which is whatever integer type the generic function was instantiated with. i should get that same integer type. Where is the problem?
This behavior appears to be intentional, not a bug, as there exists a test that asserts it (if I understand that test code correctly).
This limitation is trivial to work around, but I want to understand why it exists.
