Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Skip first element of an array in Golang

Tags:

go

I have the following code segments

for _, val := range Arr {
    // something have to do with val
}

In Arr , there might be more than 1 elements. I want to skip the first element of Arr and continue the loop from the second element.

For example if Arr contains {1,2,3,4}. With the query I just want to take {2,3,4}.

Is there a way to do that with the range query ?

like image 419
sunkuet02 Avatar asked May 25 '16 06:05

sunkuet02


2 Answers

Yes. Use this

for _, val := range Arr[1:] {
// something to do with val
}

Or in case you can get empty slice:

for i := 1; i < len(Arr); i++ {
// something to do with Arr[i]
}
like image 170
khrm Avatar answered Sep 18 '22 05:09

khrm


Use a standard for loop or the slice operator:

for _, val := range Arr[1:] {
    // Do something
}

// Or
for i := 1; i < len(Arr); i++ {
    val = Arr[i]
    // Do something
}
like image 31
T. Claverie Avatar answered Sep 21 '22 05:09

T. Claverie