Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Loop over array in Go language

Tags:

arrays

go

Is it possible to iterate over array indices in Go language and choose not all indices but throw some period (1, 2, 3 for instance.

For example,

for i, v := range array {
//do something with i,v
}

iterates over all indices in the array

What I want to know is there any chance to have something like that

for i:=1, v := range array {
//do something with i,v
i += 4
}
like image 683
angry_gopher Avatar asked Sep 02 '13 06:09

angry_gopher


People also ask

How do I iterate over an array in Go lang?

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.

Is there a foreach construct in the Go language?

Go. In Golang there is no foreach loop instead, the for loop can be used as “foreach“. There is a keyword range, you can combine for and range together and have the choice of using the key or value within the loop.

How do you iterate through a slice in Golang?

You can loop through the list items by using a for loop.


1 Answers

What's wrong with

i := 1
for _, v := range array {
    // do something
    i += 4
}

if you want i-values other than indices, or if you want to skip the indices,

for i := 1; i < len(array); i += 4 {
    v := array[i]
}

?

like image 149
Lee Daniel Crocker Avatar answered Sep 17 '22 15:09

Lee Daniel Crocker