Ok, so the golang language does not exactly have the word “while” in it. Anyway, the do-while and while-do loops can be easily implemented with a for loop.
The main difference between the do-while and while-do is that in the case of do-while, the loop will be executed at least one, even if the condition is already false. At while-do the iteration will not be executed, if the condition is false.
This is the example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
package main import ( "fmt" ) func main() { fmt.Println("while do loop:") i := 1 for i < 5 { fmt.Println(i) i++ } fmt.Println("do while loop:") j := 10 expression := true for ok := true; ok; ok = expression { fmt.Println(j) j++ if j > 5 { expression = false } } } |
And the result is quite expected:
1 2 3 4 5 6 7 |
while do loop: 1 2 3 4 do while loop: 10 |
Yup. That’s all! 🙂
And a video: