What is the difference between Go's for loop and while loop?
In Go, there is no explicit while loop keyword like in some other programming languages. Instead, Go provides a for loop that can be used as a while loop by omitting the loop initialization and post statements.
Here is an example of a **for**
loop used as a **while**
loop:
package main
import "fmt"
func main() {
sum := 0
i := 0
for i < 10 {
sum += i
i++
}
fmt.Println(sum)
}
In this example, the **for**
loop is used as a **while**
loop by omitting the loop initialization and post statements. The loop continues as long as the condition **i < 10**
is true.
The main difference between a **for**
loop and a **while**
loop is in their syntax and the fact that **for**
loops can have a loop initialization statement and a post statement. The **for**
loop is more versatile and can be used in a wider range of scenarios than a **while**
loop.