Range over arrays
Range over arrays
Use for i, v := range a to visit indexes and values in increasing index order. Use _ to ignore the index, or for i := range a for indexes only. The iteration value is a copy of the element value.
package main
import "fmt"
func main() { temps := [3]int{18, 20, 22} total := 0 for i, v := range temps { fmt.Println(i, v) total += v } fmt.Println(total)}The loop adds three readings. An empty array produces no iterations. For a two-value range over an array value, the iteration values come from the array value evaluated before the loop, not subsequent writes to the original array.
Expected output:
0 181 202 2260Update elements by index
package main
import "fmt"
func main() { a := [3]int{1, 2, 3} for _, v := range a { v *= 2 fmt.Println(v) } fmt.Println(a) for i := range a { a[i] *= 2 } fmt.Println(a)}Multiplying v changes only the local value. Assigning to a[i] updates the actual element. An index-only range with constant len(a) does not evaluate the range expression.
Expected output:
246[1 2 3][2 4 6]Try it locally
For [4]int{2,-1,0,5}, count positive values and set negative elements to zero by index. Print the count and array.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Arrays 03: Range over arrays
Check the lesson objective before moving on.
In what order does range visit array indexes?
How do you update the actual element?