In Go, there is no specific while
loop construct like in some other programming languages. However, you can simulate a while
loop using the for
loop by omitting the initialization and post statements. Here’s an example of a while
loop in Go:
i := 0
for i < 5 {
fmt.Println(i)
i++
}
In this example, the loop continues as long as the condition i < 5
is true. It initializes i
to 0 before the loop, and in each iteration, it prints the value of i
and increments it by 1 using i++
. The loop will print the numbers from 0 to 4.
You can see that the for
loop acts as a while
loop by only specifying the condition. You manually update the loop variable (i
in this case) inside the loop body to control the loop’s progression.
It’s worth noting that you can also use a for
loop without any condition to create an infinite loop, similar to a while (true)
loop. In such cases, you would typically include a break
statement to exit the loop when a certain condition is met.
i := 0
for {
fmt.Println(i)
i++
if i >= 5 {
break
}
}
In this example, the loop will continue indefinitely until the break
statement is encountered when i
becomes greater than or equal to 5.
By using the for
loop construct and controlling the loop variable and condition, you can achieve the behavior of a while
loop in Go.