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?
The idiomatic way to remove an element from a list is to loop through it exactly like you do in your example. Removing an element by value from a slice shouldn't be too common in your program since it is an O(n)
operation and there are better data structures in the language for that. Therefore, Go does not provide a built-in remove function for slices.
If you find yourself using removal by value often, consider using a set instead where removing and adding an element is O(1)
while still being iterable.
set := map[string]bool{"apples":true, "oranges":true, "melon":true}
delete(set,"melon") // is O(1)