How to Use For Loop in Go: Syntax and Examples
In Go, the
for loop is used to repeat a block of code multiple times. It has three parts: initialization, condition, and post statement, all separated by semicolons after for. You can also use it like a while loop or an infinite loop by adjusting these parts.Syntax
The for loop in Go has this basic form:
- Initialization: Runs once before the loop starts.
- Condition: Checked before each iteration; if true, the loop continues.
- Post statement: Runs after each iteration, usually to update the loop variable.
All three parts are optional, but the semicolons must remain if you include them.
go
for initialization; condition; post { // code to repeat }
Example
This example shows a for loop counting from 1 to 5 and printing each number.
go
package main import "fmt" func main() { for i := 1; i <= 5; i++ { fmt.Println(i) } }
Output
1
2
3
4
5
Common Pitfalls
Common mistakes include:
- Omitting semicolons incorrectly when using all three parts.
- Creating infinite loops by forgetting to update the loop variable.
- Using
forwithout a condition but expecting it to stop automatically.
Here is a wrong and right example:
go
package main import "fmt" func main() { // Wrong: infinite loop because i is never updated // for i := 1; i <= 5; { // fmt.Println(i) // } // Right: update i in post statement for i := 1; i <= 5; i++ { fmt.Println(i) } }
Output
1
2
3
4
5
Quick Reference
for i := 0; i < 10; i++: classic loop with init, condition, post.for condition: loop like while.for { }: infinite loop.- Use
breakto exit loops early. - Use
continueto skip to next iteration.
Key Takeaways
The Go for loop combines initialization, condition, and post statements separated by semicolons.
You can omit parts to create while-style or infinite loops.
Always update your loop variable to avoid infinite loops.
Use break and continue to control loop flow.
Semicolons are required when using multiple parts in the for loop header.