💤 While loop in Golang

April 20, 2021
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

✒️ Write to a CSV file in Go

Learn how to write data to a CSV or TSV file
introduction file

🙌 Case-insensitive string comparison in Go

Learn how to compare strings in a case-insensitive manner
introduction strings

🏁 Check if a string starts with a substring in Go

Learn how to use strings.HasPrefix() function
introduction strings