Go Basics

Go Loops

Description

Go has only one looping construct: the `for` loop. It can mimic `while` and `do-while` loops found in other languages. It also supports `range` for iterating over collections.

Pros & Cons

✅ Pros

  • Simplicity: One keyword for everything.
  • Power: Range loop is very convenient.

❌ Cons

  • None.

When to Use

Iterating over data.

Example

Various for loop styles.

// Standard loop
for i := 0; i < 5; i++ {
    fmt.Println(i)
}

// While-style
sum := 1
for sum < 100 {
    sum += sum
}

// Range
nums := []int{2, 4, 6}
for idx, val := range nums {
    fmt.Printf("%d: %d\n", idx, val)
}

Best Practices

If you only need the value in a range loop, use `for _, value := range ...`.

← Go SwitchGo Functions →