HowtoGo
Home / Basics / For Loops
Basics

For Loops

Go has exactly one looping keyword, for. There's no separate while or do-while. One flexible for covers every loop shape.

The classic three-part for loop: init, condition, post. This runs like a for loop in C, Java, or JavaScript.

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

Drop the init and post clauses and for behaves like a while loop. It runs while the condition holds.

for total < 250 {
    total += 10
}

Drop the condition entirely and you get an infinite loop. break exits it from anywhere inside the loop body.

for {
    if total >= 250 {
        break
    }
    total += 10
}

continue skips straight to the next iteration. This example uses it to ignore negative values, refunds, while summing a list of order totals.

for _, amount := range orders {
    if amount < 0 {
        continue // skip refunds
    }
    total += amount
}

Putting it together: a loop sums a list of order amounts, skips refunds with continue, and stops with break once a daily processing cap would be exceeded.

package main

import "fmt"

func main() {
    orders := []float64{120.50, -20.00, 75.25, 300.00, 40.10}
    var total float64

    for _, amount := range orders {
        if amount < 0 {
            continue // skip refunds
        }
        if total+amount > 250 {
            break // stop once we'd exceed the daily cap
        }
        total += amount
    }

    fmt.Printf("Total processed: $%.2f\n", total)
}

The $300.00 order never gets added. The loop breaks before it, since adding it would exceed the $250 cap.

Terminal
$ go run for_loops.go
Total processed: $195.75