Closed
Description
There are many scenarios where it is necessary to obtain the difference of two slices. At present, the more common method is to create a new utils package in the project and write the method implementation in it. Now that the Go standard library has a new slices package, it is recommended to add an API:
func Difference[E comparable](s1, s2 []E) []E {
var result []E
s2len := len(s2)
s1len := len(s1)
if s2len == 0 {
return s1
}
s2Map := make(map[E]bool, s2len)
for i := 0; i < s2len; i++ {
el := s2[i]
s2Map[el] = true
}
for i := 0; i < s1len; i++ {
element := s1[i]
if _, ok := s2Map[element]; !ok {
result = append(result, element)
}
}
return result
}
Similar as golang/exp#50
The full implementation golang/exp#60