For Loops

Duration: 10 min•Difficulty: Easy•

In Go, there is only one loop command, which is for. There are no while or do-while loops like other languages, but we can modify for to behave the same way.

When to use?

Use a Loop when you need to run the same block of code repeatedly, for example:

  • Printing numbers 1 to 100.
  • Reading data from a database row by row.
  • Processing each item in a shopping list.
MAIN.GO
package main
import "fmt"
func main() {
// 1. Standard Loop (Init; Condition; Post)
// Most common for fixed counts.
for i := 0; i < 5; i++ {
fmt.Println("Number:", i)
}
// 2. While-style Loop (Condition only)
// Used if the number of iterations is uncertain, depending on a condition.
j := 0
for j < 3 {
fmt.Println("While style:", j)
j++ // Manual increment to avoid infinite loop
}
}