Introduction
Sometimes you want to repeat actions until a condition changes. Using a for loop like a while loop helps you do that easily.
Sometimes you want to repeat actions until a condition changes. Using a for loop like a while loop helps you do that easily.
for condition { // code to repeat }
This form of for loop runs as long as the condition is true.
It works like a while loop in other languages.
i := 0 for i < 5 { fmt.Println(i) i++ }
count := 10 for count > 0 { fmt.Println("Counting down", count) count-- }
This program prints numbers from 1 to 5 using a for loop as a while loop.
package main import "fmt" func main() { i := 1 for i <= 5 { fmt.Printf("Number %d\n", i) i++ } }
Remember to update the variable inside the loop to avoid infinite loops.
Go does not have a separate while keyword; this for form replaces it.
Use for condition { } to repeat code while a condition is true.
This is Go's way to write a while loop.
Always change the condition inside the loop to stop it eventually.
for loop?for condition { } to act like a while loop.for i < 5 { i++ } uses for i < 5 { i++ }, which is valid Go syntax for a while loop.for condition { } without parentheses around condition.i <= 3 and increments i, printing 1, 2, 3 correctly.i := 0
for i < 3 {
fmt.Print(i, " ")
i++
}i := 0
for i < 3 {
fmt.Println(i)
}Pass the test and this pattern moves unknown