Alexander Obregon's Substack

Share this post

User's avatar
Alexander Obregon's Substack
Mutating Collections While Ranging Over Them in Go
Companion Articles

Mutating Collections While Ranging Over Them in Go

Alexander Obregon's avatar
Alexander Obregon
Aug 07, 2025
∙ Paid
1

Share this post

User's avatar
Alexander Obregon's Substack
Mutating Collections While Ranging Over Them in Go
Share
Image Source

The main article covered what range gives back and how loop values behave when you're working with slices, maps, and channels. This one picks up from there and looks at what happens when you change those collections while the loop is still running. Most range loops behave in a steady, predictable way as long as the underlying data stays put. But the moment you start modifying that data during the loop, things shift. Appending, deleting, or spinning up goroutines can all change how the loop behaves, and what happens depends entirely on the type you're working with and when the change happens.

Original Article:

What Go Ranges Actually Return Inside Loops

What Go Ranges Actually Return Inside Loops

Alexander Obregon
·
Aug 7
Read full story

Appending to Slices While Looping

The slice header in Go has three parts: a pointer to the underlying array, the current length, and the capacity. When you range over a slice, Go uses the current length value to decide how many steps to take. That length gets locked in at the start of the loop.

So what happens if you append inside the loop?

Keep reading with a 7-day free trial

Subscribe to Alexander Obregon's Substack to keep reading this post and get 7 days of free access to the full post archives.

Already a paid subscriber? Sign in
© 2025 Alexander Obregon
Privacy ∙ Terms ∙ Collection notice
Start writingGet the app
Substack is the home for great culture

Share