Remove element by value in Go list

Solution 1:

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)

Solution 2:

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