Golang Tutorial: The 'for' Loop Mastery
In Go (Golang), language design prioritizes minimalism and structural simplicity. Unlike languages such as C++, Java, or Python—which provide multiple looping constructs like for, while, and do-while—Go unifies all iterative mechanics under a single keyword: for.
This guide explores the versatility of the for loop in Go, ranging from condition-driven while-style iterations and classic 3-component loops to control statements (break/continue) and modern Go 1.22+ integer range features.
1. The Singular Looping Construct in Go
Go deliberately omits dedicated while or do-while keywords to keep language grammar simple and predictable. Every looping pattern in Go is expressed through for.
By consolidating all iterative workflows into for, Go codebases remain cohesive and easy to audit across different development teams.
2. Implementing While-Style Loops in Go
To create a standard while loop (which repeats as long as a boolean condition remains true), you supply a single condition directly after the for keyword.
Key Syntax Rules
- No Parentheses: Go does not require parentheses
()around the loop condition. - Mandatory Braces: The loop body must always be enclosed in curly braces
{}.
Code Demonstration
package main
import "fmt"
func main() {
// Variable initialization using short-hand syntax
i := 1
// While-style loop: runs while i <= 3
for i <= 3 {
fmt.Println(i)
i = i + 1 // Increment condition variable
}
}
Vertical Execution Flow
3. Creating Infinite Loops
An infinite loop runs continuously until explicitly stopped by a system signal (such as Ctrl + C in the terminal) or terminated internally via code logic (e.g., a break statement or os.Exit()).
In Go, an infinite loop is written by omitting all conditions after the for keyword:
package main
import "fmt"
func main() {
// Infinite loop pattern
for {
fmt.Println("Processing continuous background task...")
// Terminate manually using Ctrl+C in terminal
}
}
Note: Infinite loops are common in Go for building background workers, server event loops, and long-running daemons.
4. The Classic 3-Component 'for' Loop
The classic C-style for loop contains three distinct components separated by semicolons:
- Init Statement: Executed once before the first iteration (typically short-variable declaration).
- Condition Expression: Evaluated before every iteration.
- Post Statement: Executed at the end of every iteration (typically increment/decrement).
Syntax
for [ Init Statement ] ; [ Condition Expression ] ; [ Post Statement ] {
// Loop body
}
Code Demonstration
package main
import "fmt"
func main() {
// Classic 3-component loop printing numbers from 0 to 3
for i := 0; i <= 3; i++ {
fmt.Println(i)
}
}
Terminal Output:
$ go run main.go
0
1
2
3
5. Flow Control: Skipping Iterations with continue
The continue keyword bypasses the remaining code inside the loop body for the current iteration and jumps directly to the post statement (or condition evaluation).
Example Scenario
Skip processing when the variable i equals 2.
package main
import "fmt"
func main() {
for i := 0; i <= 3; i++ {
// Skip execution when i equals 2
if i == 2 {
continue
}
fmt.Println(i)
}
}
Terminal Output:
$ go run main.go
0
1
3
Notice that 2 is omitted from the output sequence.
6. Flow Control: Premature Exit with break
The break keyword immediately stops execution of the loop and transfers program control to the statement following the loop block.
package main
import "fmt"
func main() {
for i := 0; i <= 3; i++ {
if i == 2 {
break // Exits the loop entirely when i reaches 2
}
fmt.Println(i)
}
fmt.Println("Loop terminated.")
}
Terminal Output:
$ go run main.go
0
1
Loop terminated.
7. Modern Go (Go 1.22+): Range Over Integers
Starting in Go 1.22, Go introduced integer range support. This feature allows developers to loop a specified number of times (N) using range N without manually setting up classic 3-component boilerplate.
Range Properties
- Zero-indexed: Starts counting from
0. - Half-Open Interval: Range
Niterates from0up toN - 1(it excludesN).
Code Demonstration
package main
import "fmt"
func main() {
// Iterates 3 times: value takes on 0, 1, and 2
for i := range 3 {
fmt.Println(i)
}
}
Terminal Output:
$ go run main.go
0
1
2
Note: To execute a block
10times (from index0through9), you writefor i := range 10. To reach an inclusive value of10, you pass11as the range argument (for i := range 11).
8. Comparative Matrix of Go Loop Constructs
Summary and Key Takeaways
- Single Keyword Philosophy: Go features only one looping construct:
for. There are nowhileordo-whilekeywords in the language grammar. - No Parentheses: Never enclose condition expressions in parentheses
()in Goforloops. - While-Loop Emulation: Omit initialization and post-statements to create a condition-driven while loop (
for condition {}). - Infinite Loops: An unadorned
for {}block creates a continuous loop. - 3-Component Syntax: Standard index loops use
for init; condition; post {}syntax with short variable declarations (e.g.,i := 0). - Iteration Control: Use
continueto skip the remainder of the current loop pass, andbreakto exit the loop entirely. - Go 1.22+ Enhancements: Modern Go supports
for i := range N, which iterates over an integer range from0toN-1.