util/set: add Of variant of SetOf that takes variadic parameter
set.Of(1, 2, 3) is prettier than set.SetOf([]int{1, 2, 3}). I was going to change the signature of SetOf but then I noticed its name has stutter anyway, so I kept it for compatibility. People can prefer to use set.Of for new code or slowly migrate. Also add a lazy Make method, which I often find myself wanting, without having to resort to uglier mak.Set(&set, k, struct{}{}). Updates #cleanup Change-Id: Ic6f3870115334efcbd65e79c437de2ad3edb7625 Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
This commit is contained in:

committed by
Brad Fitzpatrick

parent
80decd83c1
commit
1a963342c7
@ -14,6 +14,11 @@ type Set[T comparable] map[T]struct{}
|
||||
|
||||
// SetOf returns a new set constructed from the elements in slice.
|
||||
func SetOf[T comparable](slice []T) Set[T] {
|
||||
return Of(slice...)
|
||||
}
|
||||
|
||||
// Of returns a new set constructed from the elements in slice.
|
||||
func Of[T comparable](slice ...T) Set[T] {
|
||||
s := make(Set[T])
|
||||
s.AddSlice(slice)
|
||||
return s
|
||||
@ -41,6 +46,13 @@ func (s Set[T]) AddSet(es Set[T]) {
|
||||
}
|
||||
}
|
||||
|
||||
// Make lazily initializes the map pointed to by s to be non-nil.
|
||||
func (s *Set[T]) Make() {
|
||||
if *s == nil {
|
||||
*s = make(Set[T])
|
||||
}
|
||||
}
|
||||
|
||||
// Slice returns the elements of the set as a slice. The elements will not be
|
||||
// in any particular order.
|
||||
func (s Set[T]) Slice() []T {
|
||||
|
Reference in New Issue
Block a user