A powerful, generic, and high-performance Set implementation for Go (1.23+), designed for both simplicity and advanced functional use cases.
go-set provides a flexible and efficient way to work with sets in Go using generics. It supports both standard set operations and functional programming patterns, along with a thread-safe variant for concurrent environments.
The library is built on top of native Go maps, ensuring excellent performance with minimal overhead.
No external dependencies required.
-
Generic type support:
Set[T comparable] -
Constant-time operations (average):
AddRemoveContains
-
Zero external dependencies
-
Optimized memory allocation
MapFilterReduceFlatMapAny,All,CountPartition
-
Native iteration via
iter.Seq -
Lazy evaluation support:
IterFilterIterMapIterFlatMapIter
UnionIntersectionDifferenceSymmetricDifferenceIsSubsetIsSupersetIsDisjointEquals
Min,Max,SumSortToSlice,Copy,Clear
SyncSet(thread-safe wrapper)- Built with
sync.RWMutex - Safe for concurrent reads and writes
go get github.com/encomers/go-set- Go 1.23+
package main
import (
"fmt"
set "github.com/encomers/go-set"
)
func main() {
s := set.NewSet(1, 2, 3)
s.Add(4, 5)
s.Remove(2)
fmt.Println(s.Contains(3)) // true
fmt.Println(s.Size()) // 4
fmt.Println(s.IsEmpty()) // false
}s := set.NewSet(1, 2, 3, 4, 5)
// Filter
evens := s.Filter(func(v int) bool {
return v%2 == 0
})
// Map
doubled := s.Map(func(v int) int {
return v * 2
})
// Reduce
sum := s.Reduce(0, func(acc, v int) int {
return acc + v
})for v := range s.Iter() {
fmt.Println(v)
}for v := range s.FilterIter(func(v int) bool {
return v > 2
}) {
fmt.Println(v)
}a := set.NewSet(1, 2, 3)
b := set.NewSet(3, 4, 5)
union := a.Union(b)
intersection := a.Intersection(b)
difference := a.Difference(b)
symDiff := a.SymmetricDifference(b)min := set.Min(s)
max := set.Max(s)
sum := set.Sum(s)
sorted := set.Sort(s, func(a, b int) bool {
return a < b
})s := set.NewSyncSet[int]()
s.Add(1, 2, 3)
if s.Contains(2) {
fmt.Println("exists")
}- Safe for concurrent access
- Uses read-write locking
- Some methods return non-sync
Setfor performance
- Backed by
map[T]struct{} - Iteration order is non-deterministic
- Iterators do not create snapshots (for performance)
- Use
Setfor single-threaded scenarios - Use
SyncSetwhen working with goroutines - Avoid modifying a set during iteration
- Prefer iterators for large datasets (lazy evaluation)
MIT