Transform and choose data representations

Go for Loops: Choose a Loop Form, Read Range Values, and Avoid Capture Bugs

Learn Go for-loop forms, range values for slices, maps, strings, and channels, and the loop-variable capture change announced for Go 1.22.

By Niko Minadze6 min read

Editorial illustration for Go for Loops: Range Semantics and Loop Variable Capture Before and After Go 1.22

for is Go’s only looping construct, but the right form depends on what controls the work. A counter fits a three-component loop; a changing condition fits a condition-only loop; and a loop that must run until its body decides to stop can use for {}. When traversing a collection, range supplies values whose meaning depends on the expression being ranged over. That distinction matters both when updating elements and when a loop creates functions that run later.

Choose a loop form

These examples are fragments for use inside a function that imports fmt. A three-component loop initializes i once, checks the condition before each pass, and updates i afterward:

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

When initialization and updates belong outside the header, use a condition-only loop:

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

A loop without a condition repeats until it exits. In this fragment, assume workComplete and doWork are defined:

for {
    if workComplete() {
        break
    }
    doWork()
}

break leaves the loop. continue skips the rest of the current pass; in a three-component loop, execution then proceeds toward the next pass. For example, this fragment skips i == 1 and stops before printing i == 3:

for i := 0; i < 5; i++ {
    if i == 1 {
        continue
    }
    if i == 3 {
        break
    }
    fmt.Println(i)
}

Read what range supplies

A range clause works with arrays, slices, maps, strings, and channels. For an array or slice, its two variables receive an index and an element value. Use _ to discard an unwanted index. With just one variable, a slice range loop receives the index, not the element:

values := []string{"a", "b", "c"}
for i, value := range values {
    fmt.Println(i, value)
}
for _, value := range values {
    fmt.Println(value)
}
for i := range values {
    fmt.Println(i)
}

For a map, two variables receive a key and value; one variable receives the key. This fragment does not depend on any particular order of printed pairs:

values := map[string]int{"a": 1, "b": 2}
for key, value := range values {
    fmt.Println(key, value)
}
for key := range values {
    fmt.Println(key)
}

For a string, the first value is the starting byte offset of a Unicode code point, not a count of characters seen so far. The second is its rune. For a channel, the one-variable form receives values from the channel. These are separate function-body fragments; the channel example assumes values is a defined channel supplied by the surrounding code:

for i, value := range "aé" {
    fmt.Println(i, value)
}
for value := range values {
    fmt.Println(value)
}

A range value is not the collection slot

The element value provided by a slice range loop is a copy, not an alias to the slot in the slice. In this function-body fragment, assigning a new map to value does not install it in values[i]:

values := make([]map[int]int, 2)
for _, value := range values {
    value = make(map[int]int)
    value[1] = 2
}

To replace those slice elements, use the index and assign to the collection itself:

values := make([]map[int]int, 2)
for i := range values {
    values[i] = make(map[int]int)
    values[i][1] = 2
}

The question to ask is whether the body needs the copied value or needs to change the collection element. The first loop changes only its local value variable; the second assigns to values[i].

The capture pitfall without goroutines

Concurrency is not required for the legacy loop-variable problem. This function-body fragment imports fmt, saves closures, and calls them after the first loop finishes:

values := []string{"a", "b", "c"}
var prints []func()

for _, value := range values {
    prints = append(prints, func() {
        fmt.Println(value)
    })
}
for _, print := range prints {
    print()
}

Under the older per-loop scope described in the Go loop-variable preview, each saved function refers to the same value variable, rather than retaining a snapshot from its own pass. Called after this loop, the functions encounter its final value. Under the announced per-iteration scope, each closure instead captures the variable for its own pass. The same legacy risk can be less obvious when another function retains pointers derived from a loop value.

The same problem with goroutines

This fragment belongs inside a function that imports fmt and arranges for the goroutines to finish before the function exits:

values := []string{"a", "b", "c"}
for _, value := range values {
    go func() {
        fmt.Println(value)
    }()
}

The preview says that, with legacy shared-variable semantics, goroutines in this pattern usually print c, c, and c, rather than a, b, and c in some order. It does not promise that repeated output every time. With per-iteration variables, the goroutines capture distinct values, though this fragment does not specify their printing order.

The Go 1.22 boundary described by the preview

The Go loop-variable preview was written as a Go 1.21 preview and Go 1.22 plan. It announced per-iteration rather than per-loop scope for the affected loop variables in packages contained in modules declaring go 1.22 or later. It also describes possible per-file control through //go:build lines. Read the containing module’s directive, rather than assuming the source text alone establishes which semantics apply:

go 1.22

For code using the older semantics, copy the variable inside the body before a closure or goroutine captures it. Here is the goroutine fragment with that explicit copy; as above, the surrounding function must wait for its work to finish:

values := []string{"a", "b", "c"}
for _, value := range values {
    value := value
    go func() {
        fmt.Println(value)
    }()
}

The inner declaration creates a separate variable for that pass. The same line can go before append in the saved-closure example. It remains a useful way to make intended capture explicit when reviewing code that uses legacy semantics.

When reviewing a loop, identify the range expression and which values it yields. Ask whether the body needs a copied value or the collection element. Check whether a closure, goroutine, or retained pointer can outlive the pass that created it. Finally, check the module’s go directive when reasoning about the loop-variable scope described by the preview.

Comments

No comments yet.

Leave a comment

Your comment appears after approval. Plain text only; links stay as text. Line breaks and indentation are kept.

Up to 5,000 characters. No account or email needed.

All articles

Type at least two characters.

Press <kbd>Esc</kbd> to closeOpen the search page