How to skip the second element in a slice?

Viewed 43

In this code, I have four strings in a slice but I want to skip the second one. How to do it?

Required Result

Title
Profession
Gender

Code

package main

import "fmt"

func main() {
    data := [...]string{"Title", "Description", "Profession", "Gender"}
    for _, val := range data[1:] {
        fmt.Println(val)
    }
}
3 Answers

Iterate over the entire slice and skip the second element.

First return value of range is index (starting from 0) of current element. You can use that to decide if you want to skip or not. continue keyword will immediately iterate to the next element of the inner-most loop without executing the rest of the loop body for current step.

package main

import "fmt"

func main() {
    data := [...]string{"Title", "Description", "Profession", "Gender"}
    for i, val := range data {
        if i == 1 {
            continue
        }
        fmt.Println(val)
    }
}

If your slice is always the same than you can do it like this:

package main

import "fmt"

func main() {
    data := [...]string{"Title", "Description", "Profession", "Gender"}
    for i, val := range data {
        if i == 1 {
            continue
        }
        fmt.Println(val)

    }
}

But, if you want to skip the Description no matter the slice order than you can do it like this:

func main() {
    data := [...]string{"Title", "Gender", "Profession", "Description"}
    for _, val := range data {
        if val == "Description" {
            continue
        }
        fmt.Println(val)

    }
}

In the first example you will filter by the index of the array, in the second you will filter by the actual value of the current array index.

You can use append to skip like this

package main

import "fmt"

func main() {
    idxToSkip := 1
    data := [...]string{"Title", "Description", "Profession", "Gender"}
    for _, val := range append(data[:idxToSkip], data[idxToSkip+1:]...) {
        fmt.Println(val)
    }
}
Related