Welcome To Golang By Example

Menu
  • Home
  • Blog
Menu

Find and delete in a slice in Go (Golang)

Posted on March 19, 2023March 19, 2023 by admin

There can be two cases:

Modify Original Slice

  • Keep copying to the original slice skipping the item which needs to be deleted
  • Reslice at the end
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

  • Create a new slice and keep inserting into it.
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]

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

©2023 Welcome To Golang By Example | Design: Web XP