Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove element by value in Go list

Tags:

list

slice

go

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?

like image 319
BoppreH Avatar asked Jun 26 '15 18:06

BoppreH


1 Answers

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

like image 121
Marco Järvinen Avatar answered Sep 19 '22 09:09

Marco Järvinen