Golang : Delete item from slice based on index/key position
Problem :
You want to delete an element from a slice or array and you know the index(position number) of the element. What is the quick way to delete the element?
Solution :
You can use the append()
function to sort of "skip" the element that you want to remove before copying the rest of the elements to a new slice or array.
For example :
package main
import "fmt"
func main() {
strSlice := []string{"abc", "xyz", "def", "ghi", "jkl"}
fmt.Println("Before delete")
for k, v := range strSlice {
fmt.Printf("key : %v, value : %v \n", k, v)
}
// we want to remove xyz and the index/key number associated
// with it is 1
i := 1
newSlice := append(strSlice[:i], strSlice[i+1:]...)
fmt.Println("After delete")
for k, v := range newSlice {
fmt.Printf("key : %v, value : %v \n", k, v)
}
}
Output :
Before delete
key : 0, value : abc
key : 1, value : xyz
key : 2, value : def
key : 3, value : ghi
key : 4, value : jkl
After delete
key : 0, value : abc
key : 1, value : def
key : 2, value : ghi
key : 3, value : jkl
p/s : This solution is good as long the element is not a pointer. Otherwise, you gonna have memory leak issue.
Reference :
See also : Golang : Delete duplicate items from a slice/array
By Adam Ng
IF you gain some knowledge or the information here solved your programming problem. Please consider donating to the less fortunate or some charities that you like. Apart from donation, planting trees, volunteering or reducing your carbon footprint will be great too.
Advertisement
Tutorials
+6.5k Gogland : Single File versus Go Application Run Configurations
+13.4k Golang : Find commonalities in two slices or arrays example
+21k Golang : Read a file into an array or slice example
+7.1k How to show different content from website server when AdBlock is detected?
+25.9k Golang : Convert integer to binary, octal, hexadecimal and back to integer
+44.1k Golang : Marshal and unmarshal json.RawMessage struct example
+15.6k Golang : Get number of CPU cores
+4.4k Golang : fmt.Println prints out empty data from struct
+13.2k Golang : package is not in GOROOT during compilation
+3.6k Chrome : How to block socketloop.com links in Google SERP?
+7k Golang : Auto-generate reply email with text/template package
+6k Golang : Accessing dataframe-go element by row, column and name example