A for loop repeatedly executes a block while controlling initialization, continuation, and progression. Go unifies looping under the for statement rather than providing separate while and do-while constructs. section 2.4.10
The three-part form contains optional initialization and post clauses around a required condition:
- The init statement runs once, usually creating a counter. section 2.4.10
- The Boolean condition is checked before every iteration; Go requires it in this form. section 2.4.10
- The post statement runs after each iteration, including the final one, and commonly increments the counter. section 2.4.10
- A range clause iterates through arrays with indices, values, or both; returned values are copies, so direct mutation requires an index or pointers. section 4.1.4
Counting spaces
A counter-based loop examines each character position and increments numSpaces when text[i] is a space. This pattern combines indexing, a loop condition, and a post increment. section 2.4.10
Processing streamed input
A scanner loop continues while scanner.Scan() succeeds, processes scanner.Text() on each iteration, and checks scanner.Err() afterward. A word-counting variant applies strings.Fields per scanned line and accumulates the result. section 2.8.1
Listing 2.14 Looping over string characters with a for loop
for i := 0; i < len(text); i++ {
if text[i] == ' ' {
numSpaces++
}
}
Inspect the complete character-scanning loop used to count spaces. section 2.4.10
Listing 4.11 Example loops
for i := range items {
// do something with items[i]
}
for i, item := range items {
// do something with item or items[i]
}
for i := 0; i < len(items); i++{
// do something with items[i]
}
Compare range iteration with index-based traversal. section 4.1.4
Listing 2.38 Example usage from go doc -ex bufio.NewScanner
scanner := bufio.NewScanner(os.Stdin)
for scanner.Scan() {
fmt.Println(scanner.Text())
}
if err := scanner.Err(); err != nil {
fmt.Fprintln(os.Stderr, "reading standard input:", err)
}
See the idiomatic Scanner loop and its post-loop error check. section 2.8.1


























