In Go, we use the while loop to execute a block of code until a certain condition is met.
Unlike other programming languages, Go doesn't have a dedicated keyword for a while loop. However, we can use the for loop to perform the functionality of a while loop.
Syntax of Go while loop
Here, the loop evaluates the condition. If the condition is:
true - statements inside the loop are executed and condition is evaluated againfalse - the loop terminates
Output
Here, we have initialized the number to 1.
number <= 5 is true. Hence, 1 is printed on the screen. Now, the value of number is increased to 2.number <= 5 is true. Hence, 2 is also printed on the screen and the value of number is increased to 3.number becomes 6. Then, the condition number <= 5 will be false and the loop terminates.Output
Here, we have initialized the multiplier := 1. In each iteration, the value of the multiplier gets incremented by 1 until multiplier <= 10.
In Go, we can use the same for loop to provide the functionality of a do while loop. For example,
Output
Notice the if statement inside the for loop.
This statement acts as the while clause inside a do...while loop and is used to terminate the loop.