sets

April 13, 2026 ยท View on GitHub

sink-logo

sets

sets provides a generic, unordered collection of unique values backed by a map.

It is designed to help you replace repetitive set-logic code with small functions for:

  • adding and removing items
  • checking membership and equality
  • performing set algebra operations
  • iterating over items

Overview

Use sets when you want set behavior that is easy to read, reuse, and test.

It is especially useful when:

  • you need to track unique values without duplicates
  • you need to compute intersections, unions, or differences between collections
  • membership checks are a core part of the logic

When to use it

Use sets when:

  • uniqueness is a requirement, not just a preference
  • set algebra operations like union or intersection are needed
  • you want a named abstraction over map-based deduplication

Prefer a slice when:

  • order matters
  • duplicate values are intentional
  • you need index-based access

API reference

Create a set

FunctionPurpose
NewCreates a new set, optionally seeded with items

Add or remove items

MethodPurpose
AddAdds one or more items to the set
RemoveRemoves an item from the set

Check membership

MethodPurpose
ContainsReturns true if the item exists in the set
EqualsReturns true if both sets contain the same items
SubsetReturns true if the set is a subset of another

Set algebra

MethodPurpose
IntersectReturns a new set with items common to both sets
UnionReturns a new set with all items from both sets
DifferenceReturns a new set with items in this set but not the other
SymmetricDifferenceReturns a new set with items in either set but not both

Inspect the set

MethodPurpose
IsEmptyReturns true if the set has no items
SizeReturns the number of items in the set
ValuesReturns all items as a slice
CloneReturns a shallow copy of the set
ClearRemoves all items from the set

Iterate

MethodPurpose
ApplyCalls a function for each item in the set

Serialization

MethodPurpose
ToJSONReturns the set as a JSON array ([]byte, error)
FromJSONReplaces the set contents from a JSON array; clears existing items first
MarshalJSONImplements json.Marshaler; allows sets to be used in json.Marshal
UnmarshalJSONImplements json.Unmarshaler; allows sets to be used in json.Unmarshal

Notes

  • Iteration order is not guaranteed; sets are backed by a Go map.
  • Intersect and Union optimize by iterating the smaller set.
  • New accepts optional seed items, making initialization concise.
  • Clone produces an independent copy; mutations do not affect the original.
  • Sets serialize as JSON arrays. FromJSON clears the set before populating it, so it replaces rather than merges.
  • MarshalJSON and UnmarshalJSON make sets compatible with the standard encoding/json package transparently.

Examples

Examples can be found in the test suite.