Generic Set Implementation In Go
May 14, 2025
package ds
import "iter"
type Set[T comparable] struct {
m map[T]struct{}
}
func NewSet[T comparable]() Set[T] {
return Set[T]{m: map[T]struct{}{}}
}
func NewSetFrom[T comparable](vals ...T) Set[T] {
s := NewSet[T]()
for _, v := range vals {
s.Add(v)
}
return s
}
func (s *Set[T]) Add(val T) {
s.m[val] = struct{}{}
}
func (s *Set[T]) Remove(val T) {
delete(s.m, val)
}
func (s *Set[T]) Contains(val T) bool {
_, ok := s.m[val]
return ok
}
func (s *Set[T]) Empty() bool {
return len(s.m) == 0
}
func (s *Set[T]) Iter() iter.Seq[T] {
return func(yield func(T) bool) {
for k := range s.m {
if !yield(k) {
return
}
}
}
}
Similiar: