We can't find the internet
Attempting to reconnect
Something went wrong!
Hang in there while we get back on track
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.
If this post was enjoyable or useful for you, please share it! If you have comments, questions, or feedback, you can email my personal email. To get new posts, subscribe use the RSS feed.