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: Using append
You can use the append function to remove an element from a slice by creating a new slice with all the elements except the one you want to remove.
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: Using go generics
as of Go 1.18, Go now supports generics. This means you can write code that is more reusable and type-safe, and reduce the amount of boilerplate code you need to write.
With generics, you can define functions, methods, and data structures that can work with different types of values, without having to write separate code for each type. You can specify a set of constraints on the types that a generic function or data structure can work with, and the Go compiler will check that these constraints are satisfied for any type that you pass to it.
Here's an example of a generic function that takes a slice of any type and returns a new slice with the elements in reverse order:
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:
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
None of these options protect you from an out of bounds panic..
https://go.dev/play/p/LdqJJaqbvhT
Instead.. https://go.dev/play/p/IUpbBaPLirR
Here is the updated code
https://go.dev/play/p/HraieAMMKsA