$ show deckarep/golang-set
This is a production-quality Go library that provides a generic set data structure with a comprehensive API modeled after Python's set. It offers two implementations: a thread-unsafe (fast) version backed by a `map[T]struct{}` and a thread-safe version that wraps the unsafe one with a `sync.RWMutex`. The library supports all standard set operations (add, remove, contains, union, intersection, difference, symmetric difference, subset/superset, equality, clone, pop, filter, iteration) and includes JSON and BSON serialization. It uses Go generics (requires Go 1.18+) and provides build-tag-based optimizations for Go 1.21+ (e.g., `maps.Clone`, `Sorted` function). The codebase is clean, well-tested, and benchmarked, with active maintenance and a strong user base including Ethereum, Docker, and 1Password. The architecture is simple and modular: the `Set` interface defines the contract, `threadUnsafeSet` is the core implementation, and `threadSafeSet` adds concurrency safety. The `Iterator` type provides a cancellable channel-based iteration pattern. The `Elements` function offers a Go 1.23-style iterator. The library is a drop-in replacement for any Go project needing a set collection.
The LLM identified 4 files worth highlighting for reuse:
Core implementation of the thread-unsafe set using `map[T]struct{}`. Implements all set operations efficiently with minimal overhead. The `append` and `add` private methods allow internal reuse without boolean checks. The `Pop` and `PopN` methods iterate over the map to remove arbitrary elements. The `Clear` method uses a range-delete pattern that the Go compiler optimizes. This file is the foundation of the entire library and can be reused as a standalone generic set implementation.
Defines the `Set[T]` interface with a comprehensive set of operations (Add, Append, Contains, Union, Intersect, Difference, etc.). Also provides constructor functions (`NewSet`, `NewThreadUnsafeSet`, `NewSetFromMapKeys`) and the `Elements` iterator function for Go 1.23+. The interface is well-documented and follows the Python set API. This design can be adopted as a pattern for any generic collection library.
Implements a cancellable iterator using a channel and a stop channel. The `Iterator` type provides a `C` channel for ranging and a `Stop()` method to signal early termination, which also drains remaining elements. The `newIterator` helper creates the channels. This pattern is reusable for any collection that needs a cancellable, channel-based iteration mechanism.
Provides a fallback implementation of `mapclone` for Go versions before 1.21. It manually copies the map. This is paired with `helper_1_21.go` which uses `maps.Clone` from the standard library. Demonstrates a clean build-tag pattern to leverage new standard library features while maintaining backward compatibility.