Skip to content

Instantly share code, notes, and snippets.

@duboisf
Last active September 24, 2025 19:30
Show Gist options
  • Select an option

  • Save duboisf/24d96f2a5f0cad0934bb0eea41982de1 to your computer and use it in GitHub Desktop.

Select an option

Save duboisf/24d96f2a5f0cad0934bb0eea41982de1 to your computer and use it in GitHub Desktop.
Generic golang functions to do a unique sort of elements
package sort
// SortedUniqueFunc returns a sorted list of unique elements extracted from the input slice using the provided getter function.
func SortedUniqueFunc[T any, E cmp.Ordered](ts []T, get func(T) E) []E {
elems := make(map[E]struct{})
for _, t := range ts {
elem := get(t)
elems[elem] = struct{}{}
}
return slices.Sorted(maps.Keys(elems))
}
// SortedUnique returns a sorted list of unique elements from the input slice.
func SortedUnique[T cmp.Ordered](ts []T) []T {
return SortedUniqueFunc(ts, Identity)
}
// Identity is the identity function that returns the input as is.
// Can be used for the [SortedUniqueFunc] function when the input slice is of a comparable type.
// Inspired by haskell's id function.
func Identity[E any](e E) E {
return e
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment