Go while Loop

Go doesn't have a while loop keyword like some other programming languages. However, you can achieve the same effect using a for loop with a condition expression.

The syntax for a while loop in Go is:

‮ refer‬to:theitroad.com
for condition {
    // code to be executed
}

The loop will continue to execute the code block as long as the condition is true. The condition is evaluated before each iteration of the loop.

Here's an example of a while loop in Go that prints numbers from 1 to 10:

i := 1
for i <= 10 {
    fmt.Println(i)
    i++
}

In this example, the loop will continue to execute as long as i is less than or equal to 10. The loop body prints the value of i to the console, and then the i++ statement increments the value of i by 1 at the end of each iteration.

Another way to achieve the same effect is to use a for loop with a break statement. Here's an example:

i := 1
for {
    if i > 10 {
        break
    }
    fmt.Println(i)
    i++
}

In this example, the for loop has no condition expression, so it will continue to execute indefinitely. However, the loop body contains an if statement that checks whether i is greater than 10. If i is greater than 10, the break statement is executed, which terminates the loop. Otherwise, the loop body prints the value of i to the console, and then the i++ statement increments the value of i by 1 at the end of each iteration.