Skip to main content
Set is a generic collection that holds at most one copy of each element. It provides membership tests, iteration, and the classic set algebra operations: union, intersection, and difference.

Installation

Constructor

int
required
A hint for the initial capacity of the internal map. Pass 0 if you have no estimate. This does not impose a maximum size.
The element type E must satisfy the comparable constraint so it can be used as a map key.

Methods

Membership

Add returns true when the item was already in the set, not when it was newly added. This mirrors a “was it found?” semantic consistent with the rest of the library. Check !found if you want to know whether insertion was new.

Set operations

For degenerate cases (nil or empty sets), Union, Intersection, and Difference may return the receiver or the argument directly without allocating a new set. Do not mutate the result if you still need the original sets to be unchanged.

Optional Countable interface

BasicMap also satisfies container.Countable, which adds a Len() method. Guard the call with a type assertion for forward compatibility:

Example

Iterating with Items

Items() returns an iter.Seq[E] compatible with Go 1.23+ range-over-func:
The iteration order is not guaranteed. If you need a sorted view, collect into a slice and sort it:
Set is not concurrency-safe. If multiple goroutines need to read or modify the same set concurrently, add external synchronization (for example, a sync.RWMutex).