Range loops
Remember that `range` copies element values and evaluates the range expression once before looping.
Canonical guidance
rangegives you a copy of the element value- mutate by index when the collection itself must change
- remember the ranged expression is evaluated once up front
Use when
- read-only iteration
- concise loops over slices, maps, strings, and channels
- index plus value traversal
Avoid
- editing struct elements through the copied loop variable
- taking addresses of loop variables when element identity matters
- assuming appends change what a slice
rangewill visit
Preferred pattern
for i := range users {
users[i].Active = true
}
Anti-pattern
- writing to fields on the ranged value and expecting the original slice element to change
Explanation: This anti-pattern is tempting because the loop variable looks like the element, but for most ranges it is just a copy of that value.
Why
- range loops are concise, but their value-copy semantics matter for correctness
Related pages
Sources
- The Go Programming Language Specification - Go Team
- Range loop pitfalls (#30-32) - Teiva Harsanyi