I was trying to find a way to intersect multiple slices in Golang. I found a few examples, but they all used a fixed number of slices. I wanted to be able to intersect an arbitrary number of slices.

Using generics, you can do this like this:

func Intersection[T comparable](slices ...[]T) []T {
    counts := map[T]int{}
    result := []T{}

    for _, slice := range slices {
        for _, val := range slice {
            counts[val]++
        }
    }

    for val, count := range counts {
        if count == len(slices) {
            result = append(result, val)
        }
    }

    return result
}

The idea is quite simple. We count the number of times each value appears in all slices. If the count is equal to the number of slices, then the value is present in all slices.