Proposal Details

I propose to create function Unique with the definition:

// Unique replaces runs of equal elements with a single copy.
// Unique modifies the contents of the slice s and returns the modified slice,
// which may have a smaller length.
func Unique[S ~[]E, E comparable](s S) S {}

and yes, we already have Compact, but Compact can not filter items that are not consecutive.

Example of usage:

myslice := []int{1,2,1}
filteredslice := slises.Unique(myslice) // []int{1,2}

I have already created PR for this change https://github.com/golang/go/pull/66231

Comment From: seankhliao

This was discussed in #47203 and #45955 and it is not something that we will do.

Comment From: xin-hao-2025

But the Golang repo already has it as an internal method, although not a generic version. https://github.com/golang/go/blob/master/src/go/build/build.go#L1109 Uniq and UniqFunc are very high-frequency methods.

Comment From: DeedleFake

@xin-hao-awx

~~The function that you linked to just does what slices.Compact() does and removes consecutive duplicates, not all duplicates.~~

Edit: Sorry, no it doesn't. I missed that it sorted the slice first.

I have a Uniq() method for iterators implemented in my iterator support package if you want to use that, but it's not exactly complicated to write.

Uniq and UniqFunc are very high-frequency methods.

I'm curious why you would make that contention. I've only needed them a handful of times ever as far as I remember.