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:
initializationis executed before the first iterationconditionis boolean expression evaluated before every iterationpost-conditionis executed after every iteration
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