0
0
GoHow-ToBeginner · 3 min read

How to Create an Infinite Loop in Go: Simple Guide

In Go, you create an infinite loop using the for statement without any conditions, like for { }. This loop runs forever until you stop the program or break the loop manually.
📐

Syntax

The infinite loop in Go uses the for keyword without any condition or initialization. It looks like this:

  • for { }: Runs the code inside forever.

Since there is no condition, the loop never ends on its own.

go
for {
    // code to repeat forever
}
💻

Example

This example prints "Hello" every second forever. It shows how the infinite loop keeps running until you stop the program.

go
package main

import (
    "fmt"
    "time"
)

func main() {
    for {
        fmt.Println("Hello")
        time.Sleep(1 * time.Second)
    }
}
Output
Hello Hello Hello Hello Hello ... (repeats every second)
⚠️

Common Pitfalls

Common mistakes when creating infinite loops in Go include:

  • Forgetting to add a break statement if you want to stop the loop under some condition.
  • Creating a loop that runs too fast without pauses, which can use 100% CPU.
  • Not handling exit conditions properly, causing your program to hang.

Always consider if you need a way to stop the loop or add delays.

go
package main

import "fmt"

func main() {
    // Wrong: infinite loop with no break or delay
    // for {
    //     fmt.Println("Running")
    // }

    // Right: infinite loop with break condition
    count := 0
    for {
        fmt.Println("Running")
        count++
        if count == 5 {
            break
        }
    }
}
Output
Running Running Running Running Running
📊

Quick Reference

Remember these tips for infinite loops in Go:

  • Use for { } for an infinite loop.
  • Add break to stop the loop when needed.
  • Use time.Sleep to avoid high CPU usage.

Key Takeaways

Use for { } to create an infinite loop in Go.
Add break inside the loop to stop it when needed.
Include delays like time.Sleep to prevent high CPU usage.
Infinite loops run forever unless stopped manually or by a break.
Always plan exit conditions to avoid unresponsive programs.