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.
Code
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
cURL to Python & Go ConverterTranslate curl CLI commands with headers, auth, JSON bodies, and timeouts into ready-to-run Python requests and Go net/http client code snippets.SemVer Range CheckerCheck whether a semantic version satisfies an npm-style range such as caret, tilde, comparison sets, wildcards, or hyphen ranges.SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.
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:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.