0
0
Goprogramming~5 mins

Infinite loops in Go

Choose your learning style9 modes available
Introduction

Infinite loops run forever until you stop them. They are useful when you want a program to keep working without stopping.

When you want a program to keep checking for new messages or data.
When you build a game that runs continuously until the player quits.
When you want a server to keep listening for requests all the time.
When you want to repeat an action until you manually stop it.
Syntax
Go
for {
    // code to repeat forever
}

The for keyword with empty conditions creates an infinite loop.

You can stop the loop using break or by stopping the program.

Examples
This prints "Hello" once and then stops because of break.
Go
for {
    println("Hello")
    break // stops after one print
}
This loop runs forever until the program is stopped.
Go
for {
    // do something forever
}
Sample Program

This program runs an infinite loop but stops after counting to 3 using break. It prints the count every half second.

Go
package main

import (
    "fmt"
    "time"
)

func main() {
    count := 0
    for {
        fmt.Println("Loop count:", count)
        count++
        if count >= 3 {
            fmt.Println("Stopping loop")
            break
        }
        time.Sleep(500 * time.Millisecond) // wait half a second
    }
}
OutputSuccess
Important Notes

Infinite loops can freeze your program if you don't stop them properly.

Use break inside the loop to exit when needed.

Adding a small delay like time.Sleep can prevent high CPU usage.

Summary

Infinite loops run forever unless stopped.

Use for { } in Go to create an infinite loop.

Always plan how to stop or control infinite loops to avoid problems.