#development #golang #pattern

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:

 1func Intersection[T comparable](slices ...[]T) []T {
 2    counts := map[T]int{}
 3    result := []T{}
 4
 5    for _, slice := range slices {
 6        for _, val := range slice {
 7            counts[val]++
 8        }
 9    }
10
11    for val, count := range counts {
12        if count == len(slices) {
13            result = append(result, val)
14        }
15    }
16
17    return result
18}

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.