Range Over Int For Counting Loops

Count loop iterations with for range over an integer, dropping the init-and-increment header, and reuse the index when you also need numbered slices.

GoData Integrity

Code

gosnippet
23 lines
package main

import "fmt"

func main() {
	// for range int:计数循环不再需要 i := 0; i < n; i++ 三段式
	for i := range 3 {
		fmt.Println("tick", i)
	}

	// 只要次数不要索引:直接 for range n
	attempts := 0
	for range 4 {
		attempts++
	}
	fmt.Println("attempts:", attempts)

	// 与切片配合:按索引顺序生成 1-based 编号
	names := []string{"ingest", "index", "serve"}
	for i := range names {
		fmt.Printf("%d: %s\n", i+1, names[i])
	}
}

The flow of the file

Range Over Int For Counting Loops reduces to the function main.

Repetition is confined to for i := range 3 — the rest of the file is straight-line.

Applying it

The demo output is labeled (tick, attempts:); each label names the call that printed it.

Statements that matter

for i := range names {
	fmt.Printf("%d: %s\n", i+1, names[i])
}
for i := range 3 {
	fmt.Println("tick", i)
}
for range 4 {
	attempts++
}

Interactive Tools for This Topic

FAQ

What does Range Over Int For Counting Loops print when run?
Running the file directly is enough — expect labeled output lines such as `tick`, `attempts:`.