Welcome To Golang By Example

Menu
  • Home
  • Blog
  • Contact Us
  • Support this website
Menu

Find and delete in a array in Go (Golang)

Posted on March 22, 2020March 22, 2020 by admin

There can be two cases:

Table of Contents

  • Modify Original Array
  • Do not modify the original array

Modify Original Array

  • Keep copying to the original array skipping the item which needs to be deleted
  • Reslice at the end
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]
Follow @golangbyexample

Popular Articles

Golang Comprehensive Tutorial Series

All Design Patterns in Go (Golang)

Slice in golang

Variables in Go (Golang) – Complete Guide

OOP: Inheritance in GOLANG complete guide

Using Context Package in GO (Golang) – Complete Guide

All data types in Golang with examples

Understanding time and date in Go (Golang) – Complete Guide

©2025 Welcome To Golang By Example | Design: Newspaperly WordPress Theme