Cookies management by TermsFeed Cookie Consent
Russia has invaded Ukraine and already killed tens of thousands of civilians, with many more raped or tortured. It's a genocide. We need your help. Let's fight back against the Russian regime.
Help Ukraine! Fight the Russian regime!

💤 While loop in Golang

introduction loop

Please consider supporting us by disabling your ad blocker

As with the foreach, there is no while keyword in Golang. However, we can make a while loop with the for statement. Classic for has the form of:

for initialization; condition; post-condition {

}

where:

When we omit the initialization and post-condition statements, we get the conditional for loop that has the same effect as while loop available in other programming languages:

for condition {

}

Example:

package main

import "fmt"

func main() {
    i := 1
    var gte1000 bool
    for !gte1000 {
        i *= 10
        fmt.Println(i)
        if i >= 1000 {
            gte1000 = true
        }
    }
}

Since Go’s for statement is very flexible, we can initialize the condition variable inside the loop and ignore the post-condition statement (notice ; at the end of the for declaration - we use classic for here):

package main

import "fmt"

func main() {
    i := 1
    for gte1000 := false; !gte1000; {
        i *= 10
        fmt.Println(i)
        if i >= 1000 {
            gte1000 = true
        }
    }
}

Output:

10
100
1000

♾️ Infinite loop in Go

Learn how to define a "while true" loop
introduction loop

➰ Foreach or for range loop in Go

Learn how to construct the popular programming loop
introduction loop syntax

🐉 Do-while loop in Go

Learn how to simulate a popular programming loop
introduction loop