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:
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.