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
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.
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.
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.
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
If your slices are the same length, use range
like this:
for i := range x { fmt.Println(x[i], y[i]) }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With