Skip to content

Value semantics in Go range loops

In Go, the for loop when combined with the range keyword exhibits value semantics.^[400-devops__09-Scripting-Language__golang__introduction__part-2.json__readme.md] This means that during iteration, the variable provided by the range clause receives a copy of the data element from the collection, rather than a reference to the original item.^[400-devops__09-Scripting-Language__golang__introduction__part-2.json__readme.md]

Implications for Mutation

Because the loop variable is a copy, any modifications made to it inside the loop body do not affect the original data stored in the underlying slice or array.^[400-devops__09-Scripting-Language__golang__introduction__part-2.json__readme.md] Consequently, attempting to update a field on the iterated variable will only update the temporary copy, leaving the original collection unchanged.^[400-devops__09-Scripting-Language__golang__introduction__part-2.json__readme.md]

Using the Index for Updates

To modify the actual elements within a slice during iteration, you must bypass the copy and access the element directly by its index.^[400-devops__09-Scripting-Language__golang__introduction__part-2.json__readme.md] This is typically achieved by using the second form of the for loop, which returns the index and the value (often ignored with _).^[400-devops__09-Scripting-Language__golang__introduction__part-2.json__readme.md]

By using collection[index], you reference the original memory location, allowing successful mutation of the struct or element in place.^[400-devops__09-Scripting-Language__golang__introduction__part-2.json__readme.md]

Sources

^[400-devops__09-Scripting-Language__golang__introduction__part-2.json__readme.md]