Range over integers with version awareness
Range over integers with version awareness
Since Go 1.22, for i := range n { ... } iterates from zero through n-1 when the integer n is positive. For zero or negative n it executes no iterations. In modules, the language version selected by the go directive must support integer range.
package main
import "fmt"
func main() { for i := range 3 { fmt.Println(i) }}The bound 3 produces three iterations, not four. Only one iteration variable is permitted for an integer range. Unlike a three-part loop, there is no explicit post statement. Use an ordinary for clause if you need a custom step or must support Go 1.21.
Repeat without an index
package main
import "fmt"
func main() { for range 2 { fmt.Println("tick") } for range 0 { fmt.Println("never") }}You may omit the iteration variable entirely if the index is not needed. Zero repetitions are allowed. The range expression is evaluated before the loop (subject to the specification’s constant-expression exception when applicable); changing a variable used as its bound inside the loop does not extend an integer range.
Try it locally
With Go 1.22 or later, use integer range over 4 to print the numbers 1, 2, 3, 4 by adding one to the iteration index.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Loops 06: Range over integers with version awareness
Check the lesson objective before moving on.
Which language version first supports ranging over an integer?
How many iterations does for range -2 perform?