Skip to content

Go range loop value semantics

In Go, the range loop provides a way to iterate over elements in data structures like slices and arrays. However, it exhibits specific value semantics regarding the variables it exposes within the loop block.^[400-devops-09-scripting-language-golang-introduction-part-2json-readme.md]

When iterating over a collection, the range keyword provides access to the element at each step. If a value is received (e.g., for _, video := range videos), the variable video is a copy of the element from the underlying slice, not a reference to the original element.^[400-devops-09-scripting-language-golang-introduction-part-2json-readme.md]

Mutation behavior

Because the loop variable is a copy, any mutations applied to it within the loop body will not affect the original data in the slice.^[400-devops-09-scripting-language-golang-introduction-part-2json-readme.md] Modifying the copy leaves the source slice unchanged.

To modify the original items, the loop must use the index to access the specific element in the underlying collection.^[400-devops-09-scripting-language-golang-introduction-part-2json-readme.md]

Examples

Modifying a copy (Incorrect)

In the following example, the intention is to update the description for every video. However, because video is a copy, the original slice is not modified.

for _, video := range videos {
    video.Description = video.Description + "\n Remember to Like & Subscribe!"
}

Modifying the original (Correct)

To persist changes, use the index i to update the specific position in the slice.^[400-devops-09-scripting-language-golang-introduction-part-2json-readme.md]

for i, _ := range videos {
    videos[i].Description = videos[i].Description + "\n Remember to Like & Subscribe!"
}
  • [[Go JSON unmarshaling]]
  • [[Go structs]]
  • [[Go loops]]
  • [[Value semantics vs reference semantics]]

Sources

^[400-devops-09-scripting-language-golang-introduction-part-2json-readme.md]