Home »
Golang
Infinite loop in Go (Golang)
Last Updated : July 19, 2025
An infinite loop is a loop that continues to execute endlessly because its condition is always true or omitted altogether. In Go, the most common way to create an infinite loop is by using the for
loop without a condition.
Syntax of Infinite Loop in Go
To create an infinite loop, simply write the for
keyword followed by an empty set of parentheses or no condition at all:
for {
// Loop body
}
Example: Basic Infinite Loop
In this example, the loop prints a message endlessly until it's manually stopped (e.g., with Ctrl+C
):
package main
import "fmt"
func main() {
for {
fmt.Println("This will print forever...")
}
}
When you run the above code, the output will be:
This will print forever...
This will print forever...
This will print forever...
...
Breaking Out of an Infinite Loop
To exit an infinite loop based on a condition, use the break
statement. Here's an example:
Example
The following example demonstrates how to exit an infinite loop in Go using the break statement once a certain condition is met:
package main
import "fmt"
func main() {
count := 1
for {
fmt.Println("Count is:", count)
count++
if count > 5 {
break
}
}
fmt.Println("Loop ended")
}
When you run the above code, the output will be:
Count is: 1
Count is: 2
Count is: 3
Count is: 4
Count is: 5
Loop ended
Use Cases of Infinite Loops
- Running background tasks
- Creating servers that listen continuously
- Polling for user input or external events
Avoiding Infinite Loops: Use Exit Strategies Wisely
Infinite loops can cause your program to hang or consume too many resources if not controlled properly. Always ensure there is a proper exit strategy using break
, return
, or os.Exit()
.
Exercise
Test your knowledge about infinite loops in Go.
- Which syntax creates an infinite loop in Go?
- What is the purpose of the
break
statement inside a loop?
- Which function is used to terminate a Go program immediately?
Advertisement
Advertisement