PROPERLY delete an element from Slice in GO [SOLVED]

In this tutorial we will cover different examples how to remove an element at the given index from a slice. Slices wrap arrays to give a more general, powerful, and convenient interface to sequences of data. Except for items with explicit dimension such as transformation matrices, most array programming in Go is done with slices rather than simple arrays. In today's post, I will give some examples of removing an element from a slice.

 

Golang remove from slice [Maintain the Order]

Method-1

You must move every element to the right of the deleting index one space to the left in order to maintain the order of your array. In Golang, it is  simple to accomplish this:

Advertisement
func remove(slice []int, s int) []int {
    return append(slice[:s], slice[s+1:]...)
}

This function will split the slices into 2 smaller slices: the first one is all the elements before and the other is all the elements after the element we want to delete. Then we have to shift every element in the second array by one to the left. In the below example, we will delete an element from int slice.

package main

import "fmt"

func remove(slice []int, s int) []int {
    return append(slice[:s], slice[s+1:]...)
}

func main() {
	beforeRemoveSlice := []int{1, 2, 3, 4, 5}
	indexRemove := 2

	fmt.Println("before remove:", beforeRemoveSlice)
	
	afterRemoveSlice := remove(beforeRemoveSlice, indexRemove)
	fmt.Println("after remove", afterRemoveSlice)
}

Output:

before remove: [1 2 3 4 5]
after remove [1 2 4 5]

 

Method-2

Note that, in the above example, the remove function take int slice as parameter only, we can use Go generics to implement 1 remove function for multiples data type.

package main

import "fmt"

func remove[T comparable](slice []T, s int) []T {
    return append(slice[:s], slice[s+1:]...)
}

func main() {
	beforeRemoveSlice := []int{1, 2, 3, 4, 5}
	strRemoveSlice := []string{"go", "linux", "cloud", "golang"}
	indexRemove := 2

	afterRemoveSlice := remove(beforeRemoveSlice, indexRemove)
	afterRemoveStrSlice := remove(strRemoveSlice, indexRemove)
	fmt.Println("after remove int slice:", afterRemoveSlice)
	fmt.Println("after remove str slice:", afterRemoveStrSlice)
}

Output:

after remove int slice: [1 2 4 5]
after remove str slice: [go linux golang]

 

Golang remove from slice [Unordered]

There is a significantly faster option: Replacing the element to be deleted with the element at the end of the slice and then return the n-1 first elements if ordering is not important to you.

package main

import "fmt"

func remove[T comparable](slice []T, i int) []T {
	slice[i] = slice[len(slice)-1]
    return slice[:len(slice)-1]
}

func main() {
	beforeRemoveSlice := []int{1, 2, 3, 4, 5}
	strRemoveSlice := []string{"go", "linux", "cloud", "golang"}
	indexRemove := 2

	afterRemoveSlice := remove(beforeRemoveSlice, indexRemove)
	afterRemoveStrSlice := remove(strRemoveSlice, indexRemove)
	fmt.Println("after remove int slice:", afterRemoveSlice)
	fmt.Println("after remove str slice:", afterRemoveStrSlice)
}

Output:

Advertisement
after remove int slice: [1 2 5 4]
after remove str slice: [go linux golang]

 

Summary

In this tutorial, I have shown 2 simple ways to delete an element from a slice. There are 2 things to note in the above examples:

  • The answers do not perform bounds-checking. It expects a valid index as input. Go will raise panic if any negative values or indices have a value greater than or equal to the initial len(s).
  •  The first method (shift elements) is inefficient because you may end up with moving all of the elements, which is costly.

 

References

https://go.dev/doc/tutorial/generics
https://go.dev/doc/effective_go#slices

 

Categories GO

Didn't find what you were looking for? Perform a quick search across GoLinuxCloud

If my articles on GoLinuxCloud has helped you, kindly consider buying me a coffee as a token of appreciation.

Buy GoLinuxCloud a Coffee

For any other feedbacks or questions you can either use the comments section or contact me form.

Thank You for your support!!

Leave a Comment

X