Understand the contract
range supplies iteration values according to the collection type. For a slice it supplies an index and a copy of the element value. For a map it supplies a key and a value. For a string it supplies a byte offset and a decoded rune. These pairs have different meanings.
Use _ to discard an iteration value you do not need. When modifying a slice of integers or structs, assign through its index. Changing the local value variable only changes that copy. A copied pointer still refers to its original object, so element type also affects the observed behavior.
Work through the example
The loop prints the original elements while assigning doubled values back into the slice. Its final output is [4 8 12]. Keeping the transformation explicit makes the mutation visible to a reader. For a read-only sum, iterate over values and avoid modifying the source.
package main
import "fmt"
func main() {
values := []int{2, 4, 6}
for i, value := range values {
fmt.Println(i, value)
values[i] = value * 2
}
fmt.Println(values)
}Watch this boundary
Do not depend on map iteration order, and avoid changing collection structure while learning range semantics. In particular, appending elements does not turn a range over a slice into a growing work queue. Use an explicit index-based loop or a channel when the workload can grow during processing.
Practice with a changed input
First replace values[i] = value * 2 with value *= 2 and compare the final slice. Then implement a sum that leaves all elements unchanged.
Lesson 16 of 50
View the full Go basics seriesReferences & further reading
Need help with your Go backend?
I work with engineering teams on focused Go and Kubernetes platform engagements, with limited consulting availability.
Explore Go consulting services