liveBook · Manning

Loop

As explained in 100 Go Mistakes and How to Avoid Them

A classic for loop is a Go loop construct controlled by initialization, condition, and post statements rather than a range clause.

A classic for loop evaluates its condition during every iteration. That differs from a range loop, whose input expression is evaluated once and copied before iteration begins. section 4.2 section 4.7

A growing slice can prevent termination

With s := []int{0, 1, 2}, a loop such as `for i := 0; i < len(s); i++ { s = append(s, 10) }` keeps increasing len(s) while testing it, so the termination condition is never reached. A range loop over the same slice completes after the original three iterations because it iterates over a three-element temporary copy. section 4.2

Use the loop form that matches the operation:

  • Use a classic for loop with an index when updating selected elements or controlling iteration explicitly. section 4.1.2
  • Remember that a range value is a copy: changing a copied struct does not change the slice element; update through its index instead. section 4.1.2 section 4.7
  • When deferring cleanup inside a loop, add a surrounding function so defer runs at each iteration rather than when the outer function returns. section 4.6
s := []int{0, 1, 2}
for i := 0; i < len(s); i++ {
    s = append(s, 10)
}

Inspect the classic loop whose condition depends on the continually growing slice length. section 4.2

How 100 Go Mistakes and How to Avoid Them covers it

How deep it goes
Traces condition evaluation, slice growth, copied range values, and deferred cleanup, but stops short of implementation internals.
Examples
Uses growing-slice loops, account updates, channel-driven file processing, and per-iteration deferred file closure.
What it assumes
Assumes basic Go control structures and data types while clarifying range copying, evaluation timing, and deferred execution.
What you can do after
Diagnose nontermination, copied-value mutations, and resource leaks by tracing loop conditions, element access, and defer scope.
How it connects
Connects classic for loops with range loops, slices, structs, channels, defer, maps, switch, and select.

Also explained in

Compare how 27 books explain loop →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of 100 Go Mistakes and How to Avoid Them. The section links point to the parts of the book it draws on.