Welcome To Golang By Example

Find and delete in a slice in Go (Golang)

There can be two cases:

Modify Original Slice

package main

import "fmt"

func main() {
    s := []int{"a", "b", "c", "a"}
    after := findAndDelete(s, "a")
    fmt.Println(after)
}
func findAndDelete(s []int, item int) []int {
    index := 0
    for _, i := range s {
        if i != item {
            s[index] = i
            index++
        }
    }
    return s[:index]
}

Output:

[2,3]

Do not modify the original slice

package main

import "fmt"

func main() {
    before := []int{1, 2, 3, 1}
    after := findAndDelete(before, 1)
    fmt.Println(after)
}

func findAndDelete(s []int, itemToDelete int) []int {
    var new = make([]int, len(s))
    index := 0
    for _, i := range s {
        if i != itemToDelete {
            new = append(new, i)
            index++
        }
    }
    return new[:index]
}

Output:

[2,3]