Cookies management by TermsFeed Cookie Consent

πŸ’€ While loop in Golang

introduction loop

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


Thank you for being on our site 😊. If you like our tutorials and examples, please consider supporting us with a cup of coffee and we'll turn it into more great Go examples.

Have a great day!

Buy Me A Coffee

♾️ Infinite loop in Go

Learn how to define a “while true” loop
introduction loop

➰ Foreach 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