Welcome To Golang By Example

Find and delete in a array in Go (Golang)

There can be two cases:

Modify Original Array

package main

import "fmt"

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

func findAndDelete(s [4]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 array

Create a new array and keep inserting into it.

package main

import "fmt"

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

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

Output

[2,3]