readyset
Generic sets, including sets of records identified by a key, with an opt-in thread-safe variant
About readyset
ReadySet
Generic sets for Go, with the usual set logic: union, intersection, difference, symmetric difference, subset and superset checks.
It also handles sets of records identified by a key, such as users by email or rows by ID, even when the records themselves cannot be compared with ==.
Installation
go get github.com/kastolars/readyset
Requires Go 1.23 or later.
Sets of records
import "github.com/kastolars/readyset/keyed"
type User struct {
Email string
Name string
Tags []string // a slice, so User cannot be compared with ==
}
byEmail := func(u User) string { return u.Email }
team := keyed.New(byEmail,
User{Email: "[email protected]", Name: "Ann"},
User{Email: "[email protected]", Name: "Bob"},
)
oncall := keyed.New(byEmail, User{Email: "[email protected]"})
newHires := keyed.New(byEmail, User{Email: "[email protected]", Name: "Cy"})
team.Contains(User{Email: "[email protected]"}) // true: only the key is compared
team.Difference(oncall) // Ann
team.Union(newHires) // Ann, Bob and Cy: one User per email
Without this you would keep a map[string]User, write union, intersection and difference yourself, and decide by hand what happens when two sources disagree about the same user. In keyed, two elements are the same element exactly when their keys are equal, and adding an element whose key is already present replaces the stored one.
Sets of values
When your elements are comparable (int, string, structs of comparable fields, ...), a plain readyset.Set is all you need. Two elements are the same when their values are equal.
import "github.com/kastolars/readyset"
a := readyset.New(1, 2, 3)
b := readyset.New(3, 4)
a.Union(b) // {1, 2, 3, 4}
a.Intersection(b) // {3}
a.Difference(b) // {1, 2}
| Package | Use it when | Elements are the same when |
|---|---|---|
readyset | your elements are comparable | their values are equal |
readyset/keyed | elements are not comparable (they hold slices or maps), or only part of them, like an ID, defines identity | their keys are equal |
readyset
import "github.com/kastolars/readyset"
a := readyset.New(1, 2, 3)
b := readyset.New(3, 4)
a.Add(5, 6) // variadic
a.Remove(1)
a.Contains(2) // true
a.ContainsAll(2, 3) // true: every one is present
a.ContainsAny(8, 9) // false: none is present
a.Union(b) // {2, 3, 4, 5, 6}
a.Intersection(b) // {3}
a.Difference(b) // {2, 5, 6}
a.SymmetricDifference(b) // {2, 4, 5, 6}
a.IsSubset(b) // false
a.IsProperSubset(b) // false: a proper subset is a subset that is not equal
a.IsDisjoint(b) // false
a.Equal(b) // false
a.AddSet(b) // in place: a is now the union, {2, 3, 4, 5, 6}
a.RemoveSet(b) // in place: a is now the difference, {2, 5, 6}
c := a.Clone()
c.RetainSet(b) // in place: c is now the intersection, {}
evens := a.Filter(func(n int) bool { return n%2 == 0 }) // a new set, {2, 6}
c.AddSet(a)
c.RemoveFunc(func(n int) bool { return n > 4 }) // in place; returns how many it removed (2)
e, ok := c.Pop() // remove and return an arbitrary element
readyset.Sorted(a) // []int{2, 5, 6}, ascending
readyset.Collect(slices.Values(xs)) // a set from any iter.Seq
var zero readyset.Set[string] // the zero value is an empty, usable set
zero.Add("x")
readyset/keyed
A key function maps each element to a comparable key. Two elements are the same element exactly when their keys are equal. This continues the example from "Sets of records" above.
team.Add(User{Email: "[email protected]", Name: "Robert"}) // replaces the stored Bob
u, ok := team.Get("[email protected]") // the stored record, found by key
team.ContainsKey("[email protected]") // true
team.RemoveKey("[email protected]") // remove by key alone, no User needed
team.Keys() // []string{"[email protected]"}, in no particular order
AddSet follows the same replace rule as Add. Operations between two sets compare keys only and expect the same key function on both. Union and Intersection return the receiver's elements. keyed.Sorted(team) returns the elements in ascending key order. keyed has the same RetainSet, RemoveFunc, Filter, Pop, ContainsAll, ContainsAny and proper-subset methods, plus keyed.Collect(key, seq).
Printing and JSON
Both packages print readably and encode to JSON as arrays, in a stable order (numbers numerically, strings lexically, keyed sets by key), so output never depends on map iteration order.
fmt.Println(readyset.New(10, 2, 1)) // {1, 2, 10}
b, _ := json.Marshal(readyset.New("b", "a")) // ["a","b"]
var tags readyset.Set[string]
_ = json.Unmarshal([]byte(`["go","sets"]`), &tags) // works as a struct field too
A keyed set needs its key function to decode, so create it with keyed.New before calling json.Unmarshal.
Sharing a set between goroutines
A plain Set is not safe for concurrent use. When goroutines share a set, use SyncSet, which does the locking for you. Both packages have one: readyset.NewSync(...) and keyed.NewSync(key, ...).
seen := readyset.NewSync[string]() // a *SyncSet; the zero value works too
go func() { seen.Add("a") }()
seen.Contains("a")
-
Each method is atomic, a sequence of methods is not.
if !seen.Contains(x) { seen.Add(x) }is a race, because another goroutine can addxin between.Doruns several steps under one lock:var added bool seen.Do(func(set *readyset.Set[string]) { if !set.Contains("a") { set.Add("a") added = true } }) -
Operations between two sets lock both in a fixed order.
a.Union(b)andb.Union(a)running at once cannot deadlock, anda.Union(a)is fine. -
Functions you pass in run under the lock. The callbacks of
Filter,RemoveFuncandDomust not call methods on anySyncSet, not only the same one: two callbacks that each lock the other's set can deadlock. To combine two sets useRemoveSet,RetainSet,Intersectionand the like, which lock both safely, or take aSnapshot()of the other set first. -
All()iterates over a copy taken when the loop starts, so the loop body can change the set. -
Snapshot()returns an independent plainSet, forSortedor for code that needs no locking. Its elements are copied by value, so anything they point to (a pointer, or inkeyeda slice or map inside a record) is still shared, and the lock does not protect it. -
Use a pointer and never copy one. A
SyncSetcontains a lock, andgo vetreports copies. Hold a*SyncSetin a struct field: a value field cannot be copied safely, andjson.Marshalof the struct passed by value writes{}for it.
The lock has a cost, so a plain Set stays the default: use it when one goroutine owns the set or you already hold a mutex. Uncontended, the lock adds about 2 ns to a lookup (4.6 to 6.6 ns) and about 6 ns to an Add (4.4 to 10 ns). When many cores read the same set at once they contend on the lock, and a lookup averaged about 50 ns with 18 cores. For a set that is read by many goroutines and rarely changes, share an immutable Snapshot() instead. The numbers come from go test -bench SyncCost on an Apple M5 Pro.
Recipes
// Unique values from a slice. Slice() is in random order; Sorted is not.
unique := readyset.Sorted(readyset.New(ids...))
// What changed between two snapshots.
added := current.Difference(previous)
removed := previous.Difference(current)
// Does the caller hold every permission the action needs?
if granted.IsSuperset(required) {
// ...
}
// Merge several sources into one set, then drop the blocked values.
var all readyset.Set[string] // the zero value is ready to use
for _, src := range sources {
all.AddSet(src)
}
all.RemoveSet(blocked)
// Drain a worklist: process each item once, in no particular order.
for {
item, ok := todo.Pop()
if !ok {
break
}
// ... may call todo.Add(...) for newly discovered work
}
// One record per ID, in ID order. Later records replace earlier ones.
byID := keyed.New(func(r Record) int { return r.ID }, records...)
latest := keyed.Sorted(byID)
Behaviour to know about
- Iteration order is random. Go randomises map iteration, so
Slice()andAll()return elements in no particular order. Printing and JSON are sorted for you; sort the result yourself if you need a stable order fromSlice(). - Copies share storage. Assigning a set that holds, or has held, elements to another variable shares the underlying map. Only a zero-value
Setthat has never held an element copies independently. UseClone()for an independent copy. - Elements must be equal to themselves. A NaN, or a value containing one, is ignored by
New,AddandCollect, because a set could never find or remove it again. Inkeyed, an element whose key is a NaN is ignored. - Sets of interface values can panic. In a
Set[any], adding or looking up a slice, map or function panics, as a Go map key does. Decoding JSON into one returns an error instead. - Result sets are sized for speed.
Union,IntersectionandDifferenceallocate their result for the largest it could be, which avoids regrowing the map. If you keep a small result computed from a very large input,Clone()it to release the extra memory. Setis not safe for concurrent use. Use aSyncSet(see above), or guard the set with your own mutex.- Set operations return new sets.
Union,Intersectionand the rest never modify their operands.AddSet,RemoveSetandRetainSetare the in-place forms ofUnion,DifferenceandIntersection. One difference inkeyed: for a key in both sets,AddSettakes the argument's element, likeAdd, whileUnionkeeps the receiver's.
Contributing
Pull requests are welcome. For major changes, please open an issue first to discuss what you would like to change.
Please make sure to update tests as appropriate. go test -race ./... and gofmt must pass; CI also runs staticcheck.
License
Frequently Asked Questions
What is readyset?
readyset is a Data Structures and Algorithms library for the Go programming language. Generic sets, including sets of records identified by a key, with an opt-in thread-safe variant
How do I install readyset?
Install readyset with the Go module system using `go get kastolars/readyset`. Check the repository for the current installation instructions.
What category does readyset belong to?
readyset is listed under Data Structures and Algorithms, specifically Sets.