Cookies management by TermsFeed Cookie Consent

πŸ‰ Do-while loop in Go

introduction loop

The do-while is a popular programming loop found in many languages such as C++, Java, or JavaScript. It is similar to the while loop but with the difference that the body of the do-while is executed at least once. In Go, there is no special expression to create the do-while loop, but we can easily simulate it using a for loop. We just need to ensure that it executes at least once.

The classic for has the form of:

for <initialization>; <condition>; <post-condition> {
    <loopBody>
}

To ensure that it executes at least once, the <condition> must be true for the first iteration and be dependent on the loop stop condition in subsequent iterations:

for next := true; next; next=<condition> {
    <loopBody>
}

There is also a simpler form of the do-while loop in Go, in which the <condition> of the for loop is checked after the <loopBody> and if it is not true the loop is exited:

for {
    <loopBody>
    if !<condition> {
        break
    }
}

Examples

The first version of the do-while loop:

Print the i variable if the value is less than 5:

i := 0
for next := true; next; next = i < 5 {
    fmt.Println(i)
    i++
}

Output:

0
1
2
3
4

Check that the loop is executed at least once:

i := 10
for next := true; next; next = i < 5 {
    fmt.Println(i)
    i++
}

Output:

10

The second version of the do-while loop:

Print the i variable if the value is less than 5:

i := 0
for {
    fmt.Println(i)
    i++
    if i >= 5 {
        break
    }
}

Output:

0
1
2
3
4

This version of the loop is also executed at least once πŸ˜‰:

i := 10
for {
    fmt.Println(i)
    i++
    if i >= 5 {
        break
    }
}

Output:

10

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

πŸ’€ While loop in Golang

Learn how to construct the popular programming while loop
introduction loop

➰ Foreach loop in Go

Learn how to construct the popular programming loop
introduction loop syntax