How to write a while loop in Go
Table of Contents
Go does not have a while keyword, but you can express the same logic with the for statement. It is the idiomatic way to write while-style loops in Go.
While-style loop in Go #
Classic for has the form:
for initialization; condition; post-condition {
}
where:
initializationis executed before the first iterationconditionis boolean expression evaluated before every iterationpost-conditionis executed after every iteration
When we omit the initialization and post-condition statements, we get the conditional for loop that has the same effect as while loop available in other programming languages:
for condition {
}
Example #
package main
import "fmt"
func main() {
i := 1
var gte1000 bool
for !gte1000 {
i *= 10
fmt.Println(i)
if i >= 1000 {
gte1000 = true
}
}
}
Since Go’s for statement is very flexible, we can initialize the condition variable inside the loop and ignore the post-condition statement (notice ; at the end of the for declaration - we use classic for here):
Example with inline initialization #
package main
import "fmt"
func main() {
i := 1
for gte1000 := false; !gte1000; {
i *= 10
fmt.Println(i)
if i >= 1000 {
gte1000 = true
}
}
}
Output:
100
1000
Common mistakes #
❌ Forgetting to update the condition:
for i < 10 {
fmt.Println(i)
}
✅ Always update the loop variable:
for i < 10 {
fmt.Println(i)
i++
}
❌ Using a for loop when a range loop is clearer:
for i := 0; i < len(items); i++ { /* ... */ }
✅ Prefer range for slices and arrays:
for _, item := range items { /* ... */ }
Best practices #
- Keep loop conditions simple and easy to read.
- Use
breakfor early exit andcontinueto skip iterations. - Prefer
rangewhen iterating over collections.
Related topics #
- Foreach loop in Go - iterating with range
- Do while loop in Go - emulate do-while behavior
- Infinite loop in Go - intentional endless loops
- Range over a ticker in Go - periodic loops
- Measure time in Go - timing loop work
Tested with Go 1.25+ | Last verified: December 2025 🎉