跳过Golang中数组的第一个元素

跳过Golang中数组的第一个元素

问题描述:

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 ?

我有以下代码段 p>

 用于_,val  := range Arr {
 //与val 
} 
  code>  pre> 
 
 

有关,在 Arr strong>中,可能不止 1个元素。 我想跳过 Arr strong>的第一个元素,并从第二个元素继续循环。 p>

例如,如果 Arr strong>包含{1 ,2,3,4}。 对于查询,我只想取{2,3,4}。 p>

是否可以使用范围查询来做到这一点? p> div>

Yes. Use this

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

Or

s = len(Arr)
for _, val := range Arr[1:s] {
// something have to do with val
}

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
}

convert to slice then skip first element(with the range query):

package main

import "fmt"

func main() {
    Arr := [...]int{1, 2, 3, 4}
    for _, val := range Arr[1:] {
        fmt.Println(val)
    }
}

using index to skip first element(with the range query):

package main

import "fmt"

func main() {
    Arr := [...]int{1, 2, 3, 4}
    for i, val := range Arr {
        if i == 0 {
            continue
        }
        fmt.Println(val)
    }
}

using one bool var to skip first element(with the range query):

package main

import "fmt"

func main() {
    Arr := [...]int{1, 2, 3, 4}
    first := true
    for _, val := range Arr {
        if first {
            first = false
            continue
        }
        fmt.Println(val)
    }
}

In case you what to do something different with the first value, you can do this:

for i, val := range Arr {
   if i == 0 {
       //Ignore or do something with first val   
   }else{
       // something have to do with val
   }
}