liveBook · Manning

Loop variable

As explained in Learn Go with Pocket-Sized Projects

A loop variable is a variable whose value identifies or controls the current iteration of a loop.

A loop variable identifies the current iteration. When a goroutine uses that variable after the loop advances, the value may have been overridden, so protect it before launching concurrent work. section 9.5.1

Protect loop variables in three common ways:

  • Use a Go version that guarantees safe loop-variable behavior. section 9.7
  • Shadow the variable inside the loop: p := p. The goroutine then captures the safe local copy. section 9.5.1
  • Pass the variable as a parameter to the anonymous function that starts the goroutine. section 9.5.1

Concurrent path exploration

A maze solver ranges over paths received from a channel and launches one goroutine per path. Passing p directly to the anonymous function or shadowing it prevents later channel messages from changing the path being explored. The same issue appears with map keys, map values, slice elements, and parallel table tests. section 9.5.1 section 9.7

for p := range s.pathsToExplore {
    p := p
    wg.Add(1)
    go func() {
        defer wg.Done()
        // use the local p
        s.explore(p)
    }()
    ...

Shows the shadowing pattern that gives each goroutine its own loop-variable copy. section 9.5.1

How Learn Go with Pocket-Sized Projects covers it

How deep it goes
Explains the capture hazard and three protections, but does not develop loop-variable implementation internals.
Examples
Uses concurrent maze paths, channel messages, map and slice iteration, and parallel table tests.
What it assumes
Assumes familiarity with Go loops and goroutines while demonstrating anonymous-function parameters and variable shadowing.
What you can do after
Diagnose/debug with it by recognizing and preventing incorrect values captured by goroutines in loops.
How it connects
Connects loop variables to goroutines, anonymous functions, channels, slices, maps, and parallel tests.

Also explained in

Compare how 2 books explain loop variable →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Learn Go with Pocket-Sized Projects. The section links point to the parts of the book it draws on.