How to find intersection of two slices in Go
Created
Modified
Using map cache
It's a best method for intersection two slice. Time complexity is too low. Time Complexity : O(m+n)
package main
import "fmt"
func intersection(a, b []string) ([]string, error) {
// uses empty struct (0 bytes) for map values.
m := make(map[string]struct{}, len(b))
// cached
for _, v := range b {
m[v] = struct{}{}
}
var s []string
for _, v := range a {
if _, ok := m[v]; ok {
s = append(s, v)
}
}
return s, nil
}
func main() {
s1 := []string{"a", "b"}
s2 := []string{"b", "c", "d"}
// find s1 strings in s2
s, _ := intersection(s1, s2)
fmt.Println(s)
}
[b]
You can use reflect.TypeOf for any []T.
Using simple loops
Compare each element in A to each in B. For example,
package main
import "fmt"
func intersection(a, b []string) ([]string, error) {
var s []string
for _, m := range a {
ok := false
for _, n := range b {
if m == n {
ok = true
break
}
}
if ok {
s = append(s, m)
}
}
return s, nil
}
func main() {
s1 := []string{"a", "b"}
s2 := []string{"b", "c", "d"}
// find s1 strings in s2
s, _ := intersection(s1, s2)
fmt.Println(s)
}
[b]
You can then create your own package and reuse once you settle how you want to implement it.
package intersection
func String(a []string, b []string) (inter []string, error)
func Int(a []int, b []int) (inter []int, error)
func Float64(a []Float64, b []Float64) (inter []Float64, error)