Go does not have a dedicated while keyword; instead, you use the for statement with a condition and no initialization or post statements to create a while loop. The syntax is simply for condition { }, which continues executing the block as long as the condition evaluates to true.
Here is a basic example that counts down from 5 to 1:
package main
import "fmt"
func main() {
i := 5
for i > 0 {
fmt.Println(i)
i--
}
}
You can also use this pattern for waiting on external conditions, such as checking a channel or a flag. In this case, the loop runs until a specific state changes:
package main
import (
"fmt"
"time"
)
func main() {
ready := false
go func() {
time.Sleep(2 * time.Second)
ready = true
}()
for !ready {
fmt.Print(".")
time.Sleep(100 * time.Millisecond)
}
fmt.Println("\nReady!")
}
Remember that if the condition is always true, you create an infinite loop (for { }), which is common for server main loops or event handlers. To exit these, you must use break, return, or panic inside the block. Unlike C or Java, Go's for loop is the only looping construct, so mastering this pattern is essential for control flow.