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!

πŸ‰ Do-while loop in Go

introduction loop

Please consider supporting us by disabling your ad blocker

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

♾️ 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 or for range loop in Go

Learn how to construct the popular programming loop
introduction loop syntax