Use a for loop with no initialization, condition, or post-statement, which is the idiomatic way to create an infinite loop in Go. You must explicitly break out of the loop using break, return, or panic to avoid hanging your program indefinitely.
Here is the standard syntax for an infinite loop that processes items from a channel until the channel is closed:
package main
import (
"fmt"
"time"
)
func main() {
// Create a channel to simulate work
ticker := time.NewTicker(1 * time.Second)
// The idiomatic infinite loop
for {
select {
case <-ticker.C:
fmt.Println("Ticking...")
// Simulate a condition to stop the loop
// In a real scenario, you might check a context or error
time.Sleep(100 * time.Millisecond)
default:
// Optional: do something if no tick is ready
}
// Example exit condition to prevent actual infinite hang in this demo
// Remove this in production code if you truly need an infinite loop
// break
}
// Cleanup
ticker.Stop()
}
If you need a simpler infinite loop that runs until a specific condition is met internally, you can use break to exit:
package main
import "fmt"
func main() {
count := 0
for {
count++
fmt.Printf("Iteration: %d\n", count)
if count >= 5 {
fmt.Println("Stopping loop.")
break // Explicitly exit the infinite loop
}
}
}
In Go, for is the only loop construct, so for { } is the universal pattern for infinite loops. Unlike C or Java, there is no while(true) syntax. Always ensure your infinite loop has a clear exit strategy, such as checking a context.Context for cancellation or closing a channel, to prevent resource leaks or unresponsive services.