readyset

package module
v0.1.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 20, 2026 License: MIT Imports: 6 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

ReadySet

Generic sets for Go, with the usual set logic: union, intersection, difference, symmetric difference, subset and superset checks.

Two packages, for two situations:

Package Use it when Elements are the same when
readyset your elements are comparable (int, string, structs of comparable fields, ...) 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

Requires Go 1.18 or later. The All() iterator methods are available with Go 1.23 or later.

Installation

go get github.com/kastolars/readyset

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.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.IsDisjoint(b)          // false
a.Equal(b)               // false

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.

import "github.com/kastolars/readyset/keyed"

type User struct {
    Email string
    Name  string
    Tags  []string // not comparable, so User cannot go in a readyset.Set
}

users := keyed.New(func(u User) string { return u.Email })
users.Add(User{Email: "ann@example.com", Name: "Ann"})

users.Contains(User{Email: "ann@example.com"}) // true: only the key is compared
u, ok := users.Get("ann@example.com")

users.ContainsKey("ann@example.com") // true
users.RemoveKey("ann@example.com")   // remove by key alone, no User needed
users.Keys()                         // []string{}, in no particular order

Because key equality is element equality, adding an element whose key is already present replaces the stored element. Operations between two sets compare keys only and expect the same key function on both. Union and Intersection return the receiver's elements.

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.

Behaviour to know about

  • Iteration order is random. Go randomises map iteration, so Slice() and All() return elements in no particular order. Printing and JSON are sorted for you; sort the result yourself if you need a stable order from Slice().
  • Copies share storage. Assigning a non-empty set to another variable shares the underlying map. Use Clone() for an independent copy.
  • Not safe for concurrent use. Guard a set with your own mutex if goroutines share it.
  • Operations never modify their operands. Union, Intersection and the rest return new sets.

Alternatives

  • deckarep/golang-set: mature, with thread-safe and unsafe variants.
  • hashicorp/go-set: sets, hash sets and tree sets behind a common interface.
  • A set type for the standard library has been proposed (see golang/go#47331 and the follow-up proposals). If one ships, prefer it.

ReadySet is deliberately small: no thread safety, no ordered sets, no shared collection interface.

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

MIT

Documentation

Overview

Package readyset provides generic sets for Go, with the usual set logic: union, intersection, difference, symmetric difference, and subset, superset and disjointness checks.

Set holds any comparable type, and two elements are the same element when they are equal:

a := readyset.New(1, 2, 3)
b := readyset.New(3, 4)
fmt.Println(a.Union(b))        // {1, 2, 3, 4}
fmt.Println(a.Intersection(b)) // {3}

For elements that are not comparable, or that are identified by only part of their value such as an ID, use github.com/kastolars/readyset/keyed.

Sets print with their elements in a stable order, and encode to and decode from JSON as arrays. Iteration order (Set.Slice) is random, as with Go maps.

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Set

type Set[T comparable] struct {
	// contains filtered or unexported fields
}

Set is an unordered collection of unique elements.

The zero value is an empty set that is ready to use. Methods that modify a set have pointer receivers, so call them on an addressable variable. Copying a non-empty Set copies a reference to the same underlying storage; use Set.Clone for an independent copy.

A Set is not safe for concurrent use.

func New

func New[T comparable](elements ...T) Set[T]

New returns a Set containing elements. Duplicates are ignored.

Example
package main

import (
	"fmt"

	"github.com/kastolars/readyset"
)

func main() {
	s := readyset.New(3, 1, 2, 3)
	fmt.Println(s.Len(), s.Contains(2), s.Contains(9))
}
Output:
3 true false

func (*Set[T]) Add

func (s *Set[T]) Add(elements ...T)

Add inserts elements into the set. Elements already present are ignored.

Example
package main

import (
	"fmt"

	"github.com/kastolars/readyset"
)

func main() {
	var s readyset.Set[string] // the zero value is ready to use
	s.Add("a", "b")
	s.Add("b", "c")
	fmt.Println(s.Len())
}
Output:
3

func (Set[T]) All

func (s Set[T]) All() iter.Seq[T]

All returns an iterator over the elements of the set, in no particular order. It is available when building with Go 1.23 or later.

The set must not be modified while iterating over it.

func (*Set[T]) Clear

func (s *Set[T]) Clear()

Clear removes every element from the set.

func (Set[T]) Clone

func (s Set[T]) Clone() Set[T]

Clone returns an independent copy of the set.

Example
package main

import (
	"fmt"

	"github.com/kastolars/readyset"
)

func main() {
	a := readyset.New(1, 2)
	b := a.Clone()
	b.Add(3)
	fmt.Println(a.Len(), b.Len())
}
Output:
2 3

func (Set[T]) Contains

func (s Set[T]) Contains(element T) bool

Contains reports whether element is in the set.

func (Set[T]) Difference

func (s Set[T]) Difference(other Set[T]) Set[T]

Difference returns a new set of the elements that are in s but not in other.

Example
package main

import (
	"fmt"

	"github.com/kastolars/readyset"
)

func main() {
	a := readyset.New(1, 2, 3)
	b := readyset.New(2, 3, 4)
	fmt.Println(a.Difference(b))
}
Output:
{1}

func (Set[T]) Equal

func (s Set[T]) Equal(other Set[T]) bool

Equal reports whether s and other contain exactly the same elements.

func (Set[T]) Intersection

func (s Set[T]) Intersection(other Set[T]) Set[T]

Intersection returns a new set of the elements that are in both s and other.

Example
package main

import (
	"fmt"

	"github.com/kastolars/readyset"
)

func main() {
	a := readyset.New(1, 2, 3)
	b := readyset.New(2, 3, 4)
	fmt.Println(a.Intersection(b))
}
Output:
{2, 3}

func (Set[T]) IsDisjoint

func (s Set[T]) IsDisjoint(other Set[T]) bool

IsDisjoint reports whether s and other have no elements in common.

Example
package main

import (
	"fmt"

	"github.com/kastolars/readyset"
)

func main() {
	odds := readyset.New(1, 3, 5)
	evens := readyset.New(2, 4, 6)
	fmt.Println(odds.IsDisjoint(evens))
}
Output:
true

func (Set[T]) IsEmpty

func (s Set[T]) IsEmpty() bool

IsEmpty reports whether the set has no elements.

func (Set[T]) IsSubset

func (s Set[T]) IsSubset(other Set[T]) bool

IsSubset reports whether every element of s is also in other. The empty set is a subset of every set, and every set is a subset of itself.

Example
package main

import (
	"fmt"

	"github.com/kastolars/readyset"
)

func main() {
	a := readyset.New(2, 3)
	b := readyset.New(1, 2, 3, 4)
	fmt.Println(a.IsSubset(b), b.IsSubset(a))
}
Output:
true false

func (Set[T]) IsSuperset

func (s Set[T]) IsSuperset(other Set[T]) bool

IsSuperset reports whether every element of other is also in s.

func (Set[T]) Len

func (s Set[T]) Len() int

Len returns the number of elements in the set.

func (Set[T]) MarshalJSON

func (s Set[T]) MarshalJSON() ([]byte, error)

MarshalJSON implements json.Marshaler. It encodes the set as a JSON array of its elements, in the same stable order as Set.String, so equal sets always encode to the same bytes. An empty set encodes as [].

Example
package main

import (
	"encoding/json"
	"fmt"

	"github.com/kastolars/readyset"
)

func main() {
	b, _ := json.Marshal(readyset.New("b", "a"))
	fmt.Println(string(b))
}
Output:
["a","b"]

func (*Set[T]) Remove

func (s *Set[T]) Remove(elements ...T)

Remove deletes elements from the set. Elements not present are ignored.

Example
package main

import (
	"fmt"

	"github.com/kastolars/readyset"
)

func main() {
	s := readyset.New(1, 2, 3)
	s.Remove(1, 9) // 9 is not present; that is not an error
	fmt.Println(s)
}
Output:
{2, 3}

func (Set[T]) Slice

func (s Set[T]) Slice() []T

Slice returns the elements of the set as a new slice, in no particular order. The order can differ between calls.

func (Set[T]) String

func (s Set[T]) String() string

String returns the elements in braces, separated by commas, in a stable order: numbers numerically, strings lexically, and any other value by its printed form. It implements fmt.Stringer, so a set prints readably with fmt.Println and the %v and %s verbs.

Example
package main

import (
	"fmt"

	"github.com/kastolars/readyset"
)

func main() {
	// Numbers print in numeric order, whatever order they were added in.
	s := readyset.New(10, 2, 1)
	fmt.Println(s)
}
Output:
{1, 2, 10}

func (Set[T]) SymmetricDifference

func (s Set[T]) SymmetricDifference(other Set[T]) Set[T]

SymmetricDifference returns a new set of the elements that are in exactly one of s and other.

Example
package main

import (
	"fmt"

	"github.com/kastolars/readyset"
)

func main() {
	a := readyset.New(1, 2, 3)
	b := readyset.New(2, 3, 4)
	fmt.Println(a.SymmetricDifference(b))
}
Output:
{1, 4}

func (Set[T]) Union

func (s Set[T]) Union(other Set[T]) Set[T]

Union returns a new set of the elements that are in s, in other, or in both.

Example
package main

import (
	"fmt"

	"github.com/kastolars/readyset"
)

func main() {
	a := readyset.New(1, 2, 3)
	b := readyset.New(3, 4)
	fmt.Println(a.Union(b))
}
Output:
{1, 2, 3, 4}

func (*Set[T]) UnmarshalJSON

func (s *Set[T]) UnmarshalJSON(data []byte) error

UnmarshalJSON implements json.Unmarshaler. It decodes a JSON array into the set, replacing its previous contents; duplicate elements in the array are collapsed. A JSON null leaves the set unchanged. If decoding fails the set is also left unchanged.

Example
package main

import (
	"encoding/json"
	"fmt"

	"github.com/kastolars/readyset"
)

func main() {
	type Config struct {
		Tags readyset.Set[string] `json:"tags"`
	}
	var c Config
	err := json.Unmarshal([]byte(`{"tags":["go","sets","go"]}`), &c)
	fmt.Println(err, c.Tags.Len(), c.Tags.Contains("sets"))
}
Output:
<nil> 2 true

Directories

Path Synopsis
internal
order
Package order sorts values of any type into a stable, human-friendly order, so that printed and encoded sets do not depend on map iteration order.
Package order sorts values of any type into a stable, human-friendly order, so that printed and encoded sets do not depend on map iteration order.
setlaws
Package setlaws checks the algebraic laws that every set type in this module must satisfy.
Package setlaws checks the algebraic laws that every set type in this module must satisfy.
Package keyed provides a generic Set for elements that are identified by a key rather than by their own value.
Package keyed provides a generic Set for elements that are identified by a key rather than by their own value.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL