How to Create While Loop in Go: Syntax and Examples
Go does not have a dedicated
while loop keyword. Instead, you create a while loop using the for loop with only a condition, like for condition { }, which runs as long as the condition is true.Syntax
In Go, a while loop is written using the for keyword with only a condition. The loop runs repeatedly while the condition is true.
- for condition { }: Runs the block as long as
conditionis true.
go
for condition { // code to repeat }
Example
This example counts from 1 to 5 using a while-style loop in Go.
go
package main import "fmt" func main() { i := 1 for i <= 5 { fmt.Println(i) i++ } }
Output
1
2
3
4
5
Common Pitfalls
Common mistakes include forgetting to update the loop variable inside the loop, which causes an infinite loop. Also, using a semicolon after the for condition is incorrect in Go.
go
package main import "fmt" func main() { i := 1 // Wrong: missing i++ causes infinite loop // for i <= 5 { // fmt.Println(i) // } // Correct: for i <= 5 { fmt.Println(i) i++ } }
Output
1
2
3
4
5
Quick Reference
Summary tips for creating while loops in Go:
- Use
for condition { }to create a while loop. - Always update the loop variable inside the loop to avoid infinite loops.
- Do not add semicolons after the condition.
Key Takeaways
Go uses
for with a condition to create while loops.The loop runs while the condition is true, just like a while loop.
Always update the loop variable inside the loop to prevent infinite loops.
Do not use semicolons after the condition in the for loop.
This pattern is the standard way to write while loops in Go.