A goroutine or deferred function reads a loop variable that later iterations change, before Go 1.22

tx0/go:loop-variable-captureddefaultwarningbug, concurrency

What it finds

``go for _, job := range jobs { go func() { run(job) }() } ` Before Go 1.22, the variables a for statement declares are shared by all its iterations. A goroutine or deferred function that reads one usually runs after the loop has moved on, and then sees a later value, often the last one for every goroutine. Passing the value as an argument, or copying it with job := job`, gives each function its own. Since Go 1.22 each iteration has its own variables.

The rule applies to files whose nearest go.mod names a version before 1.22. Reported are uses of a loop variable inside a function literal that the last statement of the loop body starts with go or defer, or passes to a method Go, as of an errgroup; the last statement of an if at the end counts as well. Literals that run before the iteration ends are not reported, since the loop waits for nothing else there.

From the rule's source, loop_variable_captured.rs.

Turn it on, off or suppress it

The rule runs in every tier. To turn it off for a project, set its level in tx0.toml:

tx0.toml
[rules]
"tx0/go:loop-variable-captured" = "off"

To keep one finding, suppress it with a reason. tx0 suppress ID --reason "..." writes the comment on the line before the code:

// tx0: ignore[tx0/go:loop-variable-captured] reason="..."

tx0 explain tx0/go:loop-variable-captured shows the same in the terminal. Found a false positive? Report it.