[SOLVED] How to skip the second element in a slice?

Issue

This Content is from Stack Overflow. Question asked by Kaifah Habibi

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



Solution

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


This Question was asked in StackOverflow by Kaifah Habibi and Answered by blami It is licensed under the terms of CC BY-SA 2.5. - CC BY-SA 3.0. - CC BY-SA 4.0.

people found this article helpful. What about you?