A while loop is a looping construct that allows you to run a block of code as long as a condition is true. Unlike a for loop where you determine the number of times a block should run beforehand, in a while loop, it is useful when you do not have pre-define iterations.
For example, for a while, we can use a loop to continuously prompt the user for a password until they get it right. Since the number of tries can range from 1 to infinity, a while loop is the best choice for such an operation.
But the question is, how do we create a for loop in go?
In this short guide, you will learn how to implement a while loop in go using a for loop.
Go Create While Loop
Unlike other programming languages, Go does not provide a keyword to construct a while loop. Instead, we get a for-loop construct.
One unique feature about a for loop in go is that it has three individual components, which are optional. This allows you to modify a for loop to build other looping constructs such as a while loop.
To create a while loop using the for keyword, we skip the variable initialization and the post statement and specify the loop condition.
Consider the syntax below
// run
}
We use the for keyword in the syntax above, followed by a Boolean condition. While the condition is true, we continuously execute the code inside the curly braces.
Once the condition becomes false, we terminate the loop.
Go While Loop – Examples
Let us look at a few examples to understand better how to create a while loop in go.
Example 1
Consider the example below that uses a while loop to count from 1 to 5.
import "fmt
func main() {
i := 1
for i <= 5 {
fmt.Println(i)
i++
}
}
In the example above, we start by creating a variable i and assigning it the value of 1. Next, we create a for loop to check if the value of i is less than or equal to 5. While true, we print the value of i and increment the value by 1.
The above condition evaluates to:
}
in other programming languages.
Once we run the code, we should get an output as shown:
2
3
4
5
Example 2
The example below continuously asks the user for the password as long as the provided password is incorrect.
import (
"fmt"
)
var password string
func main() {
for password != "password" {
fmt.Println("Enter the password: ")
fmt.Scanln(&password)
}
}
If we run the code above, we should see the prompt until we input the correct password as shown:
=> Enter the password:
wrong
=> Enter the password:
correct
=> Enter the password:
stop
=> Enter the password:
password
Closing
This guide taught you how to create a while loop using the for-loop construct. Thank you for reading.