Middle · Go foundations

Loop variables and toolchain semantics

Do all goroutines in a range loop still capture the same iteration variable?

Try explaining this aloud before opening the answer. State your assumptions and trace a boundary case.

Reveal a strong answer
  1. It depends on how the variable is declared and on the language version used by the module. Modern Go changed semantics for loop-declared iteration variables; repeating the old universal capture warning is inaccurate.

  2. A variable declared outside the loop and assigned by the loop can still be shared across iterations. Shared pointed-to objects and other mutable fixtures also remain shared even when each iteration variable is distinct.

  3. Inspect the go directive and actual declaration, then write explicit ownership where it improves clarity. Passing a value as a goroutine argument can make the captured value obvious, but does not deep-copy referenced data or provide a join.

Common trap

New loop semantics do not make every loop-spawned goroutine race-free or bounded.

Try it

Compare for _, v := range xs with var v T; for _, v = range xs when closures retain v.

Worked solution

In modules using the new language semantics, the first form declares per-iteration variables; the second assigns the same existing variable. For both forms, pointed-to data can still be shared and goroutines must still be joined.

Change the constraint

Why does a parallel table test still fail if every case mutates the same fake server?

How did you do?

Self-assessment, not a compiler pass or interview score. Explain the reasoning unaided before marking understood.

Not marked. Progress stays on this browser, separate from course completion.

Primary references

Checked 2026-10-20. Use documentation for your pinned runtime, driver and tool version.