For: The Only Loop

For: The Only Loop in Go: A picker in a distribution warehouse spends the whole shift doing one thing: walking the aisles and taking items off shelves.

The Analogy: The Warehouse Picking Round

A picker in a distribution warehouse spends the whole shift doing one thing: walking the aisles and taking items off shelves. The job never changes. What changes is the instruction on the job sheet. Sometimes it says "visit bays 1 through 20 in order". Sometimes it says "keep filling this pallet while there is space on it". Sometimes it says "keep working until I radio you to stop". And sometimes it hands over a printed pick list and says "work through every line on this". Four instructions, four rhythms, but the picker only ever learned one skill.

Go's for keyword is that picker. There is no while in Go, no do, no foreach, no loop, no comprehension syntax. There is exactly one loop keyword, and the four instruction styles above are its four forms: the three-clause counting loop, the condition-only loop, the clause-free infinite loop, and range. Every loop you will ever read in Go source is one of those four, which means the vocabulary you need to read someone else's loop is small enough to hold in your head permanently.

This is a deliberate trade. Other languages give you a keyword per rhythm, and the cost is that a reader has to know all of them and an author has to choose between near-identical options. Go gives you one keyword whose shape tells you the rhythm: if you see two semicolons it is counting, if you see a bare boolean it is a while, if you see nothing it runs until something breaks out, and if you see range it is walking a collection. The shape of the line is the documentation.

One more piece of the warehouse matters. Each line on the pick list gets its own docket, not a single shared clipboard sheet that gets erased and rewritten. This sounds like pedantry until the picker starts handing dockets to other workers to finish, at which point a shared sheet means everyone ends up working on the last line. Go had exactly that bug for its first fourteen years, and Go 1.22 fixed it by giving every iteration its own loop variable. It is the single most important change to for in the language's history, and the section on it below is the part of this lesson to read twice.


Syntax or Core Structure

All four forms in one program. Read the first line of each loop and say out loud which rhythm it is before reading the body.

package main

import "fmt"

func main() {
    // Form 1: three clauses. init; condition; post.
    for i := 1; i <= 3; i++ {
        fmt.Printf("three-clause i=%d\n", i)
    }

    // Form 2: condition only. This is Go's while.
    n, steps := 8, 0
    for n > 1 {
        if n%2 == 0 {
            n /= 2
        } else {
            n = 3*n + 1
        }
        steps++
    }
    fmt.Printf("condition-only steps=%d\n", steps)

    // Form 3: no clauses. Runs until something breaks out.
    budget, rounds := 100, 0
    for {
        budget -= 30
        rounds++
        if budget < 30 {
            break
        }
    }
    fmt.Printf("infinite budget=%d rounds=%d\n", budget, rounds)

    // Form 4: range, over a slice and over an integer.
    for i, name := range []string{"gb", "de"} {
        fmt.Printf("range slice %d=%s\n", i, name)
    }
    for i := range 3 {
        fmt.Printf("range int %d\n", i)
    }
}

Output:

three-clause i=1
three-clause i=2
three-clause i=3
condition-only steps=3
infinite budget=10 rounds=3
range slice 0=gb
range slice 1=de
range int 0
range int 1
range int 2

The condition-only loop halves 8 to 4 to 2 to 1 in three steps. The infinite loop subtracts 30 three times, leaves 10, and breaks because 10 is below the next installment. for i := range 3 counts 0, 1, 2 and needs Go 1.22 or newer; on an older toolchain write for i := 0; i < 3; i++.


Technical Depth: Four Forms and What Range Yields

The mapping from other languages is mechanical.

In other languagesIn Go
while condfor cond { }
while (true) / loopfor { }
do { } while (cond)for { ...; if !cond { break } }
for (init; cond; post)Identical, without the parentheses
foreach item in collfor _, item := range coll { }
for i in 0..nfor i := range n { } (Go 1.22+)

The parentheses are not optional-but-allowed, they are a syntax error, and the opening brace must be on the same line as the for. Any of the three clauses may be empty: for ; i < n; is legal but nobody writes it, because dropping the empty clauses is what gives you forms 2 and 3.

What Each Range Produces

range gives one or two values depending on what you hand it, and the second value is always a copy.

Range overFirst valueSecond value
Array, sliceIndex intCopy of the element
StringByte index intRune rune, not a byte
MapKeyCopy of the value, in randomized order
ChannelReceived valueNothing; one variable only
Integer n0 to n-1Nothing; one variable only
func(yield ...) boolYielded valueSecond yielded value if any

The last row is the range-over-function iterator added in Go 1.23, which is what powers maps.Keys and slices.Values. Omit the second variable when you do not need it, and use _ for the first when you only want the values. for range ch with no variables at all is a legal way to drain a channel.

Per-Iteration Loop Variables (Go 1.22)

Before Go 1.22, the variables declared in a for statement were created once and reused by every iteration. Any closure that captured one saw whatever value it held at the end, not the value from the iteration that created it.

funcs := make([]func() int, 0, 3)
for i := range 3 {
    funcs = append(funcs, func() int { return i })
}
for _, f := range funcs {
    fmt.Print(f(), " ")
}
fmt.Println()

Output:

0 1 2

On Go 1.21 and earlier the same loop printed 3 3 3, because all three closures shared one i that had already been incremented past the end. This was the most reported gotcha in the language's history, and almost every occurrence involved go func() { use(v) }() inside a range.

DetailBehavior
Go 1.22 and laterA fresh variable per iteration
Go 1.21 and earlierOne variable for the whole loop
What selects the behaviorThe go directive in go.mod, not the installed toolchain
AffectsVariables declared by the for itself, including range variables
Does not affectVariables declared inside the loop body, which were always per-iteration

That fourth row is the trap that remains. A module whose go.mod still says go 1.21 gets the old semantics even when built with a 2026 toolchain, because Go keeps language changes tied to the declared version so that old modules keep compiling identically. If you inherit a codebase and cannot explain a closure's value, check go.mod before you check your reasoning. The old workaround, v := v as the first line of the loop body, is now redundant but harmless, and go vet no longer flags the pattern it used to.

The Second Range Variable Is a Copy

This one costs people real debugging time. for _, it := range items copies each element into it, so assigning to it modifies the copy and the collection is untouched.

type Item struct {
    Name string
    Qty  int
}

items := []Item{{"bolt", 1}, {"nut", 2}}

for _, it := range items {
    it.Qty *= 10
}
fmt.Println("after value loop:", items)

for i := range items {
    items[i].Qty *= 10
}
fmt.Println("after index loop:", items)

Output:

after value loop: [{bolt 1} {nut 2}]
after index loop: [{bolt 10} {nut 20}]

The compiler does not warn, because writing to a local variable is perfectly legal code. To mutate elements, index into the collection as the second loop does, or hold a slice of pointers so that the copy is a copy of the pointer. The same rule explains why copying large structs in a hot loop is a real cost: for _, big := range bigStructs copies every field on every iteration, and for i := range bigStructs copies nothing.

The Range Expression Is Evaluated Once

For a slice, range captures the length before the first iteration, so growing the slice inside the loop does not give you more iterations.

s := []int{1, 2, 3}
n := 0
for range s {
    s = append(s, 99)
    n++
}
fmt.Println("iterations:", n, "len:", len(s))

Output:

iterations: 3 len: 6

This is the opposite of a for i := 0; i < len(s); i++ loop, which re-reads len(s) every iteration and would never terminate here. Ranging an array copies the array itself, so mutating arr[2] mid-loop is not visible to later iterations; ranging &arr or a slice of it avoids the copy.

Ranging a String Walks Runes, Not Bytes

A Go string is a read-only slice of bytes, but range decodes UTF-8 as it goes. The index is a byte offset and the value is a rune, so the index does not advance by one when a character needs more than one byte.

s := "caf\u00e9"
fmt.Println("len:", len(s), "runes:", utf8.RuneCountInString(s))
for i, r := range s {
    fmt.Printf("i=%d rune=U+%04X width=%d\n", i, r, utf8.RuneLen(r))
}

Output:

len: 5 runes: 4
i=0 rune=U+0063 width=1
i=1 rune=U+0061 width=1
i=2 rune=U+0066 width=1
i=3 rune=U+00E9 width=2

Four iterations over five bytes, and the last index is 3 while len(s) is 5. Indexing with s[i] instead gives a single byte, which is what you want for ASCII protocol parsing and what you do not want for anything a human typed. for i := 0; i < len(s); i++ would run five times and split the final character in half.

Labels

break and continue both accept a label, which must name an enclosing for. break outer leaves that loop entirely; continue outer jumps to its next iteration. This is the only way out of a nested loop that does not involve a flag variable or an early return, and it is the only way to break a loop from inside a switch.


Real World Example: Batching a Bulk Write With Retries

This is the loop shape you will write most often in production Go: walk a large slice in fixed-size chunks, attempt each chunk a bounded number of times, and account for what succeeded. It uses three of the four forms, the min builtin to clamp the final short batch, and a deliberate placement of err outside the retry loop.

package main

import (
    "errors"
    "fmt"
)

type Record struct {
    ID   int
    Name string
}

// sender simulates a bulk endpoint that rejects batch 2 twice before accepting it.
type sender struct{ attempts map[int]int }

func (s *sender) send(batch int, rs []Record) error {
    s.attempts[batch]++
    if batch == 2 && s.attempts[batch] < 3 {
        return errors.New("connection reset")
    }
    return nil
}

func main() {
    records := make([]Record, 0, 23)
    for i := range 23 {
        records = append(records, Record{ID: 1000 + i, Name: fmt.Sprintf("row-%02d", i)})
    }

    const batchSize = 5
    const maxAttempts = 3

    s := &sender{attempts: map[int]int{}}
    sent, failed := 0, 0

    for start := 0; start < len(records); start += batchSize {
        end := min(start+batchSize, len(records))
        batch := records[start:end]
        index := start / batchSize

        var err error
        for attempt := 1; attempt <= maxAttempts; attempt++ {
            err = s.send(index, batch)
            if err == nil {
                fmt.Printf("batch %d rows %2d-%2d attempt %d ok\n",
                    index, start, end-1, attempt)
                break
            }
            fmt.Printf("batch %d rows %2d-%2d attempt %d failed: %v\n",
                index, start, end-1, attempt, err)
        }

        if err != nil {
            failed += len(batch)
            continue
        }
        sent += len(batch)
    }

    fmt.Printf("sent=%d failed=%d batches=%d\n",
        sent, failed, (len(records)+batchSize-1)/batchSize)
}

Output:

batch 0 rows  0- 4 attempt 1 ok
batch 1 rows  5- 9 attempt 1 ok
batch 2 rows 10-14 attempt 1 failed: connection reset
batch 2 rows 10-14 attempt 2 failed: connection reset
batch 2 rows 10-14 attempt 3 ok
batch 3 rows 15-19 attempt 1 ok
batch 4 rows 20-22 attempt 1 ok
sent=23 failed=0 batches=5

The outer loop is a three-clause loop whose post statement steps by batchSize rather than by one, which is the whole trick to chunking. end := min(start+batchSize, len(records)) clamps the last batch to the three records that remain, so there is no special case after the loop and no risk of slicing past the end. Because slice bounds are half-open, records[start:end] and start < len(records) agree about where the data stops, and printing end-1 is the only place the inclusive number is needed.

var err error sits outside the inner loop on purpose. Declaring it with := inside would scope it to the loop body and the if err != nil check afterwards would not compile; keeping it outside means the variable holds the outcome of the last attempt, which is exactly what decides whether the batch counts as sent or failed. The inner loop breaks on the first success, so a batch that works immediately costs one call, and maxAttempts bounds the worst case at three. There is no else anywhere: success breaks, failure falls through to the next attempt.

continue after a failed batch skips the sent += len(batch) line and moves to the next chunk, so one bad batch does not abandon the remaining work. That is a policy decision, not a technical one. The alternative, break, stops at the first permanently failing batch and is the right choice when the batches must be applied in order. Swapping those two keywords changes the guarantee your program offers its caller, which is worth a comment in real code.

Two things are missing on purpose. batch := records[start:end] does not copy the records; it points into the same backing array, which is why passing batches around is cheap and also why a callee that retains one keeps the whole array alive. And a real retry loop would sleep between attempts with an exponentially growing delay, which was left out here because printing durations would make the output different on every run. The loop structure is unchanged by adding it: one time.Sleep before the next attempt.


Common Mistakes

  1. Looking for while. It does not exist. for cond { } is the whole answer, and for { } is the infinite version.
  1. Wrapping the clauses in parentheses. for (i := 0; i < n; i++) is a syntax error, not a style choice.
  1. Assigning to the second range variable and expecting the collection to change. It is a copy. Index into the collection instead.
  1. Trusting closures in a loop without checking go.mod. Per-iteration variables arrived in Go 1.22, and a module still declaring go 1.21 keeps the old shared-variable behavior.
  1. Treating the string range index as a character count. It is a byte offset, so it skips values whenever a character needs more than one byte.
  1. Appending to a slice while ranging it and expecting the new items to be visited. The length is captured once.
  1. Using break inside a switch inside a loop. It leaves the switch only. Label the loop.
  1. Declaring the error with := inside a retry loop and testing it after. It is out of scope; declare it before the loop.
  1. Forgetting to clamp the final chunk. records[start : start+batchSize] panics on the short last batch. Use min.
  1. Relying on map iteration order. It is deliberately randomized per run. Collect the keys and sort them.

Best Practices

  • Pick the simplest form that expresses the rhythm: range over a collection, a bare condition for a while, three clauses only when you actually need the counter.
  • Use for i := range n for a plain count on Go 1.22 or newer, and keep the three-clause form when the step is not one.
  • Range by index when you intend to mutate elements or when the elements are large structs.
  • Set the go directive in go.mod to a version at or above 1.22 so loop variables are per-iteration, and delete the old v := v shadowing lines once you have.
  • Bound every retry loop with a maximum attempt count, and declare the error variable outside it so the outcome survives.
  • Clamp chunk boundaries with min instead of writing a special case for the final partial batch.
  • Label loops that must be terminated from inside a nested loop or a switch, and name the label after what is being scanned.
  • Sort anything derived from a map before printing it, so the loop's output is reproducible.

Practice Exercises

  1. Four Rhythms, One Task: Sum the integers from 1 to 100 four times: with a three-clause loop, a condition-only loop, an infinite loop with break, and for i := range 101. Confirm all four produce 5050 and write one line on which form you would choose in review and why.
  1. Prove the Copy: Build a slice of at least four structs with a numeric field. Try to double the field with for _, v := range, print the slice, then do it with for i := range and print again. Then repeat with a []*Item and explain why the value loop now works.
  1. Bytes Versus Runes: Take a string containing at least one multi-byte character. Print len, the rune count, and every (index, rune width) pair from a range. Then walk it with for i := 0; i < len(s); i++ and record how the two loops disagree about both the number of iterations and the final index.
  1. Chunk and Retry: Write a batching loop over 47 items with a batch size of 8, where a fake sender fails batches whose index is even on their first attempt only. Print one line per attempt, bound attempts at three, and finish with a summary of sent and failed counts. Then change the failure to permanent for one batch and try both continue and break on failure, stating in one sentence which guarantee each version gives.