Skip to main content
  1. Tutorials/

How to write a while loop in Go

··2 mins

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:

  • initialization is executed before the first iteration
  • condition is boolean expression evaluated before every iteration
  • post-condition is 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 break for early exit and continue to skip iterations.
  • Prefer range when iterating over collections.

Tested with Go 1.25+ | Last verified: December 2025 🎉