Introducing Radical.sh

Forget Code launches a powerful code generator for building API's

Remove an element from slice in Go

Slice elements cannot be directly removed from slice. Instead first the index of element in found, once the position is identified another list can be created by ignoring the position of the identified element.

package main

import (
    "fmt"
    "sort"
)

func main() {

    personNameSlice := make([]string, 0)

    personNameSlice = append(personNameSlice, "hello")

    personNameSlice = append(personNameSlice, "world")

    searchedIndex := sort.SearchStrings(personNameSlice, "world")

    if searchedIndex < len(personNameSlice) {
        fmt.Printf("Element is found in index %d \n", searchedIndex)

        personNameSlice = removeIndex(personNameSlice, searchedIndex)

        fmt.Printf("%v \n", personNameSlice)
    } else {
        fmt.Printf("Element not found")
    }

}

func removeIndex(slice []string, index int) []string {
    return append(slice[:index], slice[index+1:]...)
}


Output
Element is found in index 1
[hello]