Gaaker Go

Golang Range iterate over an array

The range form of the for loop can iterate over an array.

When using for range to iterate over an array, two values will be returned for each iteration. The first value is the subscript of the current element, and the second value is a copy of the subscript element.

for ix, val := range coll {
    // do something
}

The following is a complete code example.

package main

import "fmt"

func main() {
    letters := [3]string{"a", "b", "c"}

    for index, letter := range letters {
        fmt.Printf("Index: %d Value:%s\n", index, letter)
    }
}

Below is the program output:

Index: 0 Value:a
Index: 1 Value:b
Index: 2 Value:c
< Range iterate over an array Range iterate over an array >