Skip to content

proposal: slices: add difference functionΒ #58730

Closed
@cuishuang

Description

@cuishuang

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

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions