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 ?
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
}
}