I have a list of elements and I want to remove one of them, by value. In Python this would be
l = ["apples", "oranges", "melon"]
l.remove("melon")
print(l) # ["apples", "orange"]
What is the equivalent in Go? I found a slice trick to remove an element by index, but it's not very readable, still requires me to find the index manually and only works for a single item type:
func remove(l []string, item string) {
for i, other := range l {
if other == item {
return append(l[:i], l[i+1:]...)
}
}
}
There's the list.List
structure, but it's not generic and thus requires tons of type-castings to use.
What is the idiomatic way of removing an element from a list?
In generic Go (1.18) the filter function works on any comparable
type
func remove[T comparable](l []T, item T) []T {
for i, other := range l {
if other == item {
return append(l[:i], l[i+1:]...)
}
}
return l
}
Try it here https://go.dev/play/p/ojlYkvf5dQG?v=gotip
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With