Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

range

go

To iterate over an array, slice, string, map, or channel, we can use

for _, x := range []int{1, 2, 3} {   // do something } 

How can I iterate over two slices or maps simultaneously? Is there something like following in python?

for x, y in range([1, 2, 3], [4, 5, 6]):     print x, y 
like image 645
waitingkuo Avatar asked Jan 20 '15 14:01

waitingkuo


People also ask

How do I iterate an array of objects in Golang?

Explanation: The variable i is initialized as 0 and is defined to increase at every iteration until it reaches the value of the length of the array. Then the print command is given to print the elements at each index of the array one by one.

How do you iterate a slice in Golang?

Code explanation Line 4: Program execution in Golang starts from the main() function. Line 7: We declare and initialize the slice of numbers, n . Line 10: We declare and initialize the variable sum with the 0 value. Line 13: We traverse through the slice using the for-range loop.

How do you use range in Golang?

In Golang Range keyword is used in different kinds of data structures in order to iterates over elements. The range keyword is mainly used in for loops in order to iterate over all the elements of a map, slice, channel, or an array.


2 Answers

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 
like image 59
Simone Carletti Avatar answered Sep 24 '22 17:09

Simone Carletti


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

for i := range x {     fmt.Println(x[i], y[i]) } 
like image 43
Ainar-G Avatar answered Sep 24 '22 17:09

Ainar-G