In Go (golang), how to iterate two arrays, slices, or maps using one `range`

You cannot, but if they are the same length you can use the index from range.

package main

import (
    "fmt"
)

func main() {
    r1 := []int{1, 2, 3}
    r2 := []int{11, 21, 31}

    if len(r1) == len(r2) {
        for i := range r1 {
            fmt.Println(r1[i])
            fmt.Println(r2[i])
        }
    }
}

It returns

1
11
2
21
3
31

You can do this, at the cost of creating a new array (which may or may not be a deal breaker for you)

for _, i := range append([]int{1, 2, 3}, []int{4, 5, 6, 7}...) {
    fmt.Printf("%v\n", i)
}

Note it works with different length arrays. See https://play.golang.org/p/DRCI_CwSjA for a playground example.


If your slices are the same length, use range like this:

for i := range x {
    fmt.Println(x[i], y[i])
}

Tags:

Range

Go