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
+7k Golang : How to iterate a slice without using for loop?
+4.7k JQuery : Calling a function inside Jquery(document) block
+16.5k Golang : Get the IPv4 and IPv6 addresses for a specific network interface
+6.9k Golang : Get environment variable
+37.4k Golang : Comparing date or timestamp
+16.4k Golang : Gzip file example
+10.3k Golang : Interfacing with PayPal's IPN(Instant Payment Notification) example
+8.7k Golang : Go as a script or running go with shebang/hashbang style
+17.3k How to enable MariaDB/MySQL logs ?
+22.6k Golang : Calculate time different
+10.1k Golang : Convert file unix timestamp to UTC time example
+12.2k Elastic Search : Return all records (higher than default 10)