golang-set
golang-set copied to clipboard
Feature Request: Support creating a set from a generic slice with a key selector function
Request a new feature allowing creation a set from a generic slice, where a key selector function can be provided. This would be useful in cases where we have complex structures and want to generate sets based on specific fields or derived values.
Proposed Function Signature
The function could look something like this:
func NewFromSlice[E any, T comparable](vals []E, f func(e E) T) Set[T] {
s := NewSet[T]()
for _, v := range vals {
s.Add(f(v))
}
return s
}
Usage
type Person struct {
Name string
Age int
}
people := []Person{
{Name: "Alice", Age: 30},
{Name: "Bob", Age: 25},
}
namesSet := NewFromSlice(people, func(p Person) string {
return p.Name
})