💤 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

➰ Foreach loop in Go

Learn how to construct the popular programming loop
introduction loop

🖨️ Convert string to []byte or []byte to string in Go

Learn the difference between a string and a byte slice
introduction strings slice

🧠 Print the memory address of a variable in Go

Learn how to find and print the address of a variable or pointer
introduction pointer slice