Before Go1.22
This range loop:
after compilation is semantically equivalent to:
From this, we can note a couple of important details:
- The range loop expression
exp
is evaluated only once and is assigned to a temporary variable (a copy of the original) - The variable
v
is a single variable that takes different values in each loop iteration - The variable
v
is a copy of the loop element’s value - The variable
i
is a single variable that takes different values in each loop iteration - The variable
i
is a copy of the loop index’s value
After Go1.22 (Loopvar Experiment)
This 3-clause for loop:
after compilation is semantically equivalent to:
This range loop:
after compilation is semantically equivalent to:
From this, we can note a couple of important details:
- The range loop expression
exp
is evaluated only once and is assigned to a temporary variable (a copy of the original) - The variable
v
is a newly declared variable at each iteration - The variable
v
is a copy of the loop element’s value - The variable
i
is a newly declared variable at each iteration - The variable
i
is a copy of the loop index’s value
References
- 100 Go Mistakes and How to Avoid Them. Teiva Harsanyi
- Go Range Loop Internals
- Range · golang/go Wiki · GitHub
- CommonMistakes · golang/go Wiki · GitHub
- LoopvarExperiment · golang/go Wiki · GitHub
- Fixing For Loops in Go 1.22 - The Go Programming Language
- CommonMistakes · golang/go Wiki · GitHub
- Go internals: capturing loop variables in closures - Eli Bendersky’s website
- Proposal: Less Error-Prone Loop Variable Scoping
- The Go Programming Language Specification - The Go Programming Language
- Data Race Patterns in Go | Uber Blog