The while loop in Golang

The while loop is a very important construct in general programming. But in Go, there is no loop called while. There are only for-loops. The while loops can be emulated using the for-loops in Go. So, here are some examples of how it can be done.

How to construct while loop in Golang?

The while loop in Go is the for-loop. There is no while loop in Go.

i := 0
for i < 10 {                      // emulates while (i < 10) {}
        // do something
}

While true loop

There is a loop construct in C-like languages – the while true loop, which is essentially an infinite for-loop. The infinite for construct is really simple.

for {
       // do something
}

there is an alternative way to do the same.

for true {       // same as before
       // ...
} 

Emulating the do-while loop

The do-while loops can be emulated as well using just the for-loop. Here is an example showing just that.

for {
        // do something
        if !condition {      // the condition stops matching
                break        // break out of the loop
        }
}

These are the ways by which the while loops can be emulated using just the for loop. There are no particular needs for the while-loop in Go programming. The for loop can do all of that and is suitable for just every need.