While True: Looping in Go

· 93 words · 1 minute read

In Go, the traditional while true loop, found in many programming languages, can done through the for keyword. Below are two alternative versions, a for can work as an infinite loop without any parameters, or with a true boolean.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
package main

import (
    "fmt"
    "time"
)

func main() {

    // while true loop
    for {
        fmt.Println("Infinite Loop 1")
        time.Sleep(time.Second)
    }

    // Alternative Version
    for true {
        fmt.Println("Infinite Loop 2")
        time.Sleep(time.Second)
    }
}

Image of Author Edd Turtle

Author:  Edd Turtle

Edd is the Lead Developer at Hoowla, a prop-tech startup, where he spends much of his time working on production-ready Go and PHP code. He loves coding, but also enjoys cycling and camping in his spare time.

See something which isn't right? You can contribute to this page on GitHub or just let us know in the comments below - Thanks for reading!