sets

package module
v0.11.3 Latest Latest
Warning

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

Go to latest
Published: Feb 16, 2026 License: MPL-2.0 Imports: 9 Imported by: 0

README

Sets

ci status Go Report Card GoDoc

A generics based go set package that supports modern go features like iterators.

NOTE: This is currently a WIP. I don't expect to make any breaking API changes atm, but am not able to rule it out yet.

If you like this repo, please consider checking out my iterator tools repo.

Install

Use go get to install this package.

go get github.com/freeformz/sets

Features

  • Generics based implementation.
  • Common, minimal interface based Set type.
  • Iterator support in the Set type and set methods.
  • Multiple set implementations:
    • New() -> Map based set;
    • NewLocked() -> Map based that uses a lock to be concurrency safe;
    • NewSyncMap() -> sync.Map based (concurrency safe);
    • NewOrdered() -> ordered set (uses a map for indexes and a slice for order);
    • NewLockedOrdered() -> ordered set that is concurrency safe.
  • sets package functions align with standard lib packages like slices and maps.
  • Implement as much as possible as package functions, not Set methods.
  • Exhaustive unit tests via rapid.
  • Somewhat exhaustive examples.

Usage

Package Level Examples

Set Example

OrderedSet Example

JSON

Sets marshal to/from JSON as JSON arrays. A JSON array with repeated values unmarshaled to a Set will not preserve duplicates. An empty Set marshals to []. OrderedSets preserve order when {un,}marshaling, while Sets do not.

Sets of types that don't have a JSON equivalent can't be marshaled to and/or from JSON w/o an error. For instance a Set of an interface type can marshal to json, but can't then un-marshal back to Go w/o an error.

SQL

All set types implement sql.Scanner and driver.Valuer, allowing them to be used directly with database/sql. Values are stored as JSON arrays.

Set Helpers

These helpers work on all Set types, including OrderedSets.

  • sets.Elements(aSet) : Elements of the set as a slice.
  • sets.AppendSeq(aSet,sequence) : Append the items in the sequence (an iterator) to the set.
  • sets.RemoveSeq(aSet,sequence) : Remove the items in the sequence (an iterator) from the set.
  • sets.Union(aSet,bSet) : Returns a new set (of the same underling type as aSet) with all elements from both sets.
  • sets.Intersection(aSet,bSet) : Returns a new set (of the same underlying type as aSet) with elements that are in both sets.
  • sets.Difference(aSet,bSet) : Returns a new set (of the same underlying type as aSet) with elements that are in the first set but not in the second set.
  • sets.SymmetricDifference(aSet,bSet) : Returns a new set (of the same underlying type as aSet) with elements that are not in both sets.
  • sets.Subset(aSet,bSet) : Returns true if all elements in the first set are also in the second set.
  • sets.Superset(aSet, bSet) : Returns true if all elements in the second set are also in the first set.
  • sets.Equal(aSet, bSet) : Returns true if the two sets contain the same elements.
  • sets.Disjoint(aSet, bSet) : Returns true if the two sets have no elements in common.
  • sets.ContainsSeq(aSet, sequence) : Returns true if the set contains all elements in the sequence. Empty sets are considered to contain only empty sequences.
  • sets.Iter2(sequence) : Returns a (int,V) iterator where the int represents a "pseudo" index.
  • sets.Max(aSet) : Returns the max element in the set as determined by the max builtin.
  • sets.Min(aSet) : Returns the min element in the set as determined by the min builtin.
  • sets.Chunk(aSet,n) : Chunks the set into n sets of equal size. The last set will have fewer elements if the cardinality of the set is not a multiple of n.
  • sets.IsEmpty(aSet) : Returns true if the set is empty, otherwise false.
  • sets.MapBy(aSet, func(v V) X { return ... }) bSet : Maps the elements of the set to a new set.
  • sets.MapTo(aSet, bSet, func(v V) X { return ... }) : Maps the elements of aSet into bSet.
  • sets.MapToSlice(aSet, func(v V) X { return ... }) aSlice : Maps the elements of the set to a new slice.
  • sets.Filter(aSet, func(v V) bool { return true/false }) bSet : Filters the elements of the set and returns a new set.
  • sets.Reduce(aSet, X, func(X, K) X { return ... }) X : Reduces the set to a single value.
  • sets.ForEach(aSet, func(v V)) : calls the provided function with each set member.
  • sets.FilterTo(aSet, bSet, func(v V) bool { return true/false }) : Filters the elements of aSet and adds matching elements to bSet.
  • sets.Any(aSet, func(v V) bool { return true/false }) : Returns true if any element in the set satisfies the predicate. Short-circuits on the first match.
  • sets.All(aSet, func(v V) bool { return true/false }) : Returns true if all elements in the set satisfy the predicate. Short-circuits on the first non-match.
  • sets.ContainsAll(aSet, elements...) : Returns true if the set contains all of the provided elements.
  • sets.ContainsAny(aSet, elements...) : Returns true if the set contains at least one of the provided elements.
  • sets.Random(aSet) : Returns a random element from the set without removing it. O(1) for ordered sets, O(n) for unordered sets.

OrderedSet Helpers

These helpers work on all OrderedSet types.

  • sets.EqualOrdered(aOrderedSet, bOrderedSet) : Returns true if the two OrderedSets contain the same elements in the same order.
  • sets.IsSorted(aOrderedSet) : Returns true if the OrderedSet is sorted in ascending order.
  • sets.Reverse(aOrderedSet) : Returns a new OrderedSet with the elements in the reverse order of the original OrderedSet.
  • sets.Sorted(aOrderedSet) : Return a copy of aOrderedSet with the elements sorted in ascending order. Does not modify the original set.
  • sets.ReduceRight(aSet, X, func(X, K) X { return ... }) X : Reduces the set to a single value in reverse order.
  • sets.ForEachRight(aSet, func(K) { ... }) : calls the provided function with each set member in reverse order.
  • sets.First(aOrderedSet) : Returns the first element of the ordered set, or (zero, false) if empty.
  • sets.Last(aOrderedSet) : Returns the last element of the ordered set, or (zero, false) if empty.

Custom Set Types

You can implement your own set types as long as they conform to the interfaces and can use the package level functions as they do not rely on any internal implementation details.

TODOs

  • Ordered rapid tests that test the OrderedSet bits like the normal Set bits are tested.

Documentation

Overview

A set package with various set helper functions and set types. Supports tha latest Go versions and features including generics and iterators. The package is designed to be simple and easy to use alongside the standard library.

Example (Json)
set := NewOrderedWith(1.0, 1.2, 1.3, 1.4, 1.5)
b, err := json.Marshal(set)
if err != nil {
	fmt.Println(err)
}
fmt.Println(string(b))

set2 := NewOrdered[float32]()
if err := json.Unmarshal(b, &set2); err != nil {
	fmt.Println(err)
}
fmt.Println(set2)
Output:

[1,1.2,1.3,1.4,1.5]
OrderedSet[float32]([1 1.2 1.3 1.4 1.5])

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func All added in v0.11.1

func All[K comparable](s Set[K], f func(K) bool) bool

All returns true if all elements in the set satisfy the predicate. Returns true for an empty set (vacuous truth).

Example
set := NewWith(2, 4, 6)

if All(set, func(i int) bool { return i%2 == 0 }) {
	fmt.Println("all elements are even")
}

set.Add(3)
if !All(set, func(i int) bool { return i%2 == 0 }) {
	fmt.Println("not all elements are even")
}
Output:

all elements are even
not all elements are even

func Any added in v0.11.1

func Any[K comparable](s Set[K], f func(K) bool) bool

Any returns true if any element in the set satisfies the predicate. Returns false for an empty set.

Example
set := NewWith(1, 2, 3, 4, 5)

if Any(set, func(i int) bool { return i > 3 }) {
	fmt.Println("set has element > 3")
}

if !Any(set, func(i int) bool { return i > 10 }) {
	fmt.Println("set has no element > 10")
}
Output:

set has element > 3
set has no element > 10

func AppendSeq

func AppendSeq[K comparable](s Set[K], seq iter.Seq[K]) int

AppendSeq appends all elements from the sequence to the set.

Example
ints := NewWith(5, 3)

// adds 2,4,1 to the set since 5 and 3 already exist
added := AppendSeq(ints, slices.Values([]int{5, 3, 2, 4, 1}))
fmt.Println(added)
Output:

3

func Chunk

func Chunk[K comparable](s Set[K], n int) iter.Seq[Set[K]]

Chunk the set into n sets of equal size. The last set will have fewer elements if the cardinality of the set is not a multiple of n. Panics if n <= 0.

Example
ints := NewOrderedWith(1, 2, 3, 4, 5)

// this example test won't work with an unordered set
// as the order of the chunks is based on the order of
// the set elements, which isn't stable in an unordered set
chunks := Chunk(ints, 2)
for chunk := range chunks {
	fmt.Println(chunk)
	for v := range chunk.Iterator {
		fmt.Println(v)
	}
}
Output:

OrderedSet[int]([1 2])
1
2
OrderedSet[int]([3 4])
3
4
OrderedSet[int]([5])
5

func ContainsAll added in v0.11.1

func ContainsAll[K comparable](s Set[K], elements ...K) bool

ContainsAll returns true if the set contains all of the provided elements. Returns true if no elements are provided (vacuous truth).

Example
set := NewWith(1, 2, 3, 4, 5)

if ContainsAll(set, 1, 3, 5) {
	fmt.Println("set contains 1, 3, and 5")
}

if !ContainsAll(set, 1, 6) {
	fmt.Println("set does not contain both 1 and 6")
}
Output:

set contains 1, 3, and 5
set does not contain both 1 and 6

func ContainsAny added in v0.11.1

func ContainsAny[K comparable](s Set[K], elements ...K) bool

ContainsAny returns true if the set contains at least one of the provided elements. Returns false if no elements are provided.

Example
set := NewWith(1, 2, 3)

if ContainsAny(set, 3, 4, 5) {
	fmt.Println("set contains at least one of 3, 4, 5")
}

if !ContainsAny(set, 6, 7, 8) {
	fmt.Println("set contains none of 6, 7, 8")
}
Output:

set contains at least one of 3, 4, 5
set contains none of 6, 7, 8

func ContainsSeq

func ContainsSeq[K comparable](s Set[K], seq iter.Seq[K]) bool

ContainsSeq returns true if the set contains all elements in the sequence. Empty sets are considered to contain only empty sequences.

Example
ints := New[int]()
if ContainsSeq(ints, slices.Values([]int{})) {
	fmt.Println("Empty set contains empty sequence")
}

ints.Add(5)
ints.Add(3)
ints.Add(2)

if ContainsSeq(ints, slices.Values([]int{3, 5})) {
	fmt.Println("3 and 5 are present")
}

if !ContainsSeq(ints, slices.Values([]int{3, 5, 6})) {
	fmt.Println("6 is not present")
}
Output:

Empty set contains empty sequence
3 and 5 are present
6 is not present

func Disjoint

func Disjoint[K comparable](a, b Set[K]) bool

Disjoint returns true if the two sets have no elements in common.

Example
a := NewWith(5, 3)
b := NewWith(2, 4)

if Disjoint(a, b) {
	fmt.Println("a and b are disjoint")
}

b.Add(3)
if !Disjoint(a, b) {
	fmt.Println("a and b are not disjoint now")
}
Output:

a and b are disjoint
a and b are not disjoint now

func Elements

func Elements[K comparable](s Set[K]) []K

Elements of the set as a slice. This is a convenience wrapper around slices.Collect(s.Iterator)

Example
ints := NewWith(5, 3, 2)

// []T is returned
elements := Elements(ints)
for _, i := range elements {
	fmt.Println(i)
}
// Unsorted output:
// 2
// 3
// 5

func Equal

func Equal[K comparable](a, b Set[K]) bool

Equal returns true if the two sets contain the same elements.

Example
a := NewWith(5, 3)
b := NewWith(5, 3)

if Equal(a, b) {
	fmt.Println("a and b are equal")
}

// how to compare two sets using [cmp.Diff] - pass `cmp.Comparer(Equal[T])`
if diff := cmp.Diff(a, b, cmp.Comparer(Equal[int])); diff != "" {
	fmt.Println(diff)
} else {
	fmt.Println("no diff")
}

b.Add(2)
if !Equal(a, b) {
	fmt.Println("a and b are not equal now")
}
Output:

a and b are equal
no diff
a and b are not equal now

func EqualOrdered

func EqualOrdered[K cmp.Ordered](a, b OrderedSet[K]) bool

EqualOrdered returns true if the two OrderedSets contain the same elements in the same order. cmp.Compare is used to compare elements.

Example
a := NewOrderedWith(5, 3, 1)
b := NewOrderedWith(5, 3, 1)

if EqualOrdered(a, b) {
	fmt.Println("a and b are equal")
}

// how to compare two ordered sets using [cmp.Diff] - pass `cmp.Comparer(EqualOrdered[T])`
if diff := cmp.Diff(a, b, cmp.Comparer(EqualOrdered[int])); diff != "" {
	fmt.Println(diff)
} else {
	fmt.Println("no ordered diff")
}

b.Add(2)
if !EqualOrdered(a, b) {
	fmt.Println("a and b are not equal now")
}
Output:

a and b are equal
no ordered diff
a and b are not equal now

func FilterTo added in v0.8.0

func FilterTo[K comparable](s Set[K], d Set[K], f func(K) bool)

FilterTo applies the function to each element in the set and adds the elements for which the function returns true to the destination set.

func First added in v0.11.1

func First[K cmp.Ordered](s OrderedSet[K]) (K, bool)

First returns the first element of the ordered set. If the set is empty, the second return value is false.

Example
set := NewOrderedWith(5, 3, 1)

if v, ok := First(set); ok {
	fmt.Println(v)
}

empty := NewOrdered[int]()
if _, ok := First(empty); !ok {
	fmt.Println("empty set")
}
Output:

5
empty set

func ForEach added in v0.8.0

func ForEach[K comparable](s Set[K], f func(K))

ForEach calls the function with each element in the set.

Example
set := NewWith(3, 1, 2)

ForEach(set, func(i int) {
	fmt.Println(i)
})
Output:

1
2
3

func ForEachRight added in v0.8.0

func ForEachRight[K cmp.Ordered](s OrderedSet[K], fn func(k K))
Example
set := NewOrderedWith(3, 1, 2)

ForEachRight(set, func(i int) {
	fmt.Println(i)
})
Output:

2
1
3

func IsEmpty added in v0.6.1

func IsEmpty[K comparable](s Set[K]) bool

IsEmpty returns true if the set is empty.

Example
set := New[int]()
if IsEmpty(set) {
	fmt.Println("set is empty")
}

set.Add(5)
if !IsEmpty(set) {
	fmt.Println("set is not empty")
}
Output:

set is empty
set is not empty

func IsSorted

func IsSorted[K cmp.Ordered](s OrderedSet[K]) bool

IsSorted returns true if the OrderedSet is sorted in ascending order. cmp.Less is used to compare elements.

Example
ints := NewOrderedWith(2, 3, 5)

if IsSorted(ints) {
	fmt.Println("ints is sorted")
}

ints.Add(4)
if !IsSorted(ints) {
	fmt.Println("ints is not sorted now")
}

ints.Sort()
if IsSorted(ints) {
	fmt.Println("ints is sorted")
}
Output:

ints is sorted
ints is not sorted now
ints is sorted

func Iter2

func Iter2[K comparable](iter iter.Seq[K]) func(func(i int, k K) bool)

Iter2 is a helper function that simplifies iterating over a set when an "index" is needed, by providing a pseudo-index to the yield function. The index is not stable across iterations. The yield function is called for each element in the set. If the yield function returns false, the iteration is stopped.

Example
ints := NewOrderedWith(1, 2, 3, 4, 5)

// this example test won't work with an unordered set
// as the iter2 function relies on the order of the set
// elements, which isn't stable in an unordered set
for i, v := range Iter2(ints.Iterator) {
	fmt.Println("idx:", i, "value:", v)
}
Output:

idx: 0 value: 1
idx: 1 value: 2
idx: 2 value: 3
idx: 3 value: 4
idx: 4 value: 5

func Last added in v0.11.1

func Last[K cmp.Ordered](s OrderedSet[K]) (K, bool)

Last returns the last element of the ordered set. If the set is empty, the second return value is false.

Example
set := NewOrderedWith(5, 3, 1)

if v, ok := Last(set); ok {
	fmt.Println(v)
}

empty := NewOrdered[int]()
if _, ok := Last(empty); !ok {
	fmt.Println("empty set")
}
Output:

1
empty set

func MapTo added in v0.8.0

func MapTo[K comparable, V comparable](s Set[K], d Set[V], f func(K) V)

MapTo applies the function to each element in the set and adds the results to the destination set.

Example
set := NewOrderedWith(3, 1, 2)

dest := New[string]()
MapTo(set, dest, func(i int) string {
	return fmt.Sprintf("%d=%d*2", i*2, i)
})
for i := range dest.Iterator {
	fmt.Println(i)
}
Output:

6=3*2
2=1*2
4=2*2

func MapToSlice added in v0.8.0

func MapToSlice[K comparable, V any](s Set[K], f func(K) V) []V

MapToSlice applies the function to each element in the set and returns a slice with the results.

Example
set := NewWith(3, 1, 2)

mapped := MapToSlice(set, func(i int) string {
	return fmt.Sprintf("%d=%d*2", i*2, i)
})
for _, i := range mapped {
	fmt.Println(i)
}
Output:

6=3*2
2=1*2
4=2*2

func Max

func Max[K cmp.Ordered](s Set[K]) K

Max element in the set. Set must be a set of cmp.Ordered elements. Panics if the set is empty.

Example
ints := NewWith(3, 5, 2)

max := Max(ints)
fmt.Println(max)
Output:

5

func Min

func Min[K cmp.Ordered](s Set[K]) K

Min element in the set. Set must be a set of cmp.Ordered elements. Panics if the set is empty.

Example
ints := NewWith(3, 2, 5)

min := Min(ints)
fmt.Println(min)
Output:

2

func Random added in v0.11.1

func Random[K comparable](s Set[K]) (K, bool)

Random returns a random element from the set without removing it. The second return value is false if the set is empty. For ordered sets, this is O(1) via indexed access. For unordered sets, this is O(n) via iteration.

Example
set := NewWith(42)

// with a single element, Random always returns that element
v, ok := Random(set)
if ok {
	fmt.Println(v)
}

empty := New[int]()
_, ok = Random(empty)
if !ok {
	fmt.Println("empty set")
}
Output:

42
empty set

func Reduce added in v0.8.0

func Reduce[K comparable, O any](s Set[K], initial O, f func(agg O, k K) O) O

Reduce applies the function to each element in the set and returns the accumulated value. "initial" is the initial value of the accumulator. The function is called with the accumulator and each element in turn. The result of the function is the new accumulator value. The final accumulator value is returned.

Example
set := NewWith(3, 1, 2)

sum := Reduce(set, 0, func(agg, v int) int {
	return agg + v
})
fmt.Println(sum)
Output:

6

func ReduceRight added in v0.8.0

func ReduceRight[K cmp.Ordered, O any](s OrderedSet[K], initial O, fn func(agg O, k K) O) O

ReduceRight reduces the set from right to left using the given function. "initial" is the initial value of the accumulator. The function is called with the accumulator and the element backwards. The result of the function is the new accumulator value. The final accumulator value is returned.

Example
set := NewOrderedWith(3, 1, 2)

sum := ReduceRight(set, 0, func(agg, v int) int {
	fmt.Println(v)
	return agg + v
})
fmt.Println(sum)
Output:

2
1
3
6

func RemoveSeq

func RemoveSeq[K comparable](s Set[K], seq iter.Seq[K]) int

RemoveSeq removes all elements from the set that are in the sequence.

Example
ints := NewWith(5, 3, 2)

// removes 2 from the set since 5 and 3 exist
removed := RemoveSeq(ints, slices.Values([]int{2, 4, 1}))
fmt.Println(removed)
Output:

1

func Subset

func Subset[K comparable](a, b Set[K]) bool

Subset returns true if all elements in the first set are also in the second set.

Example
a := NewWith(5, 3)
b := NewWith(5, 3, 2)

if Subset(a, b) {
	fmt.Println("a is a subset of b")
}

if !Subset(b, a) {
	fmt.Println("b is not a subset of a")
}
Output:

a is a subset of b
b is not a subset of a

func Superset

func Superset[K comparable](a, b Set[K]) bool

Superset returns true if all elements in the second set are also in the first set.

Example
a := NewWith(5, 3)
b := NewWith(5, 3, 2)

if !Superset(a, b) {
	fmt.Println("a is not a superset of b")
}

if Superset(b, a) {
	fmt.Println("b is a superset of a")
}
Output:

a is not a superset of b
b is a superset of a

Types

type Locked added in v0.9.0

type Locked[M comparable] struct {
	sync.RWMutex
	// contains filtered or unexported fields
}

Locked is a concurrency safe wrapper around a Set[M]. It uses a read-write lock to allow multiple readers to access the set concurrently, but only one writer at a time. The set is not ordered and does not guarantee the order of elements when iterating over them. It is safe for concurrent use.

func NewLocked

func NewLocked[M comparable]() *Locked[M]

NewLocked returns an empty *Locked[M] that is safe for concurrent use.

Example
set := NewLocked[string]()
set.Add("a")
set.Add("b")
set.Add("c")
set.Add("b")
fmt.Println(set.Cardinality())
Output:

3

func NewLockedFrom

func NewLockedFrom[M comparable](seq iter.Seq[M]) *Locked[M]

NewLockedFrom returns a new *Locked[M] filled with the values from the sequence.

Example
m := []string{"a", "b", "c", "b"}
set := NewLockedFrom(slices.Values(m))
fmt.Println(set.Cardinality())
Output:

3

func NewLockedWith

func NewLockedWith[M comparable](m ...M) *Locked[M]

NewLockedWith returns a *Locked[M] with the values provided.

Example
set := NewLockedWith("a", "b", "c", "b")
fmt.Println(set.Cardinality())
Output:

3

func (*Locked[M]) Add added in v0.9.0

func (s *Locked[M]) Add(m M) bool

Add an element to the set. Returns true if the element was added, false if it was already present.

func (*Locked[M]) Cardinality added in v0.9.0

func (s *Locked[M]) Cardinality() int

Cardinality returns the number of elements in the set.

func (*Locked[M]) Clear added in v0.9.0

func (s *Locked[M]) Clear() int

Clear the set and returns the number of elements removed.

func (*Locked[M]) Clone added in v0.9.0

func (s *Locked[M]) Clone() Set[M]

Clone returns a new set of the same underlying type.

func (*Locked[M]) Contains added in v0.9.0

func (s *Locked[M]) Contains(m M) bool

Contains returns true if the set contains the element.

func (*Locked[M]) Iterator added in v0.9.0

func (s *Locked[M]) Iterator(yield func(M) bool)

Iterator yields all elements in the set. It holds a read lock for the duration of iteration. Calling any method that modifies the set while iteration is happening will block until the iteration is complete.

func (*Locked[M]) MarshalJSON added in v0.9.0

func (s *Locked[M]) MarshalJSON() ([]byte, error)

MarshalJSON implements json.Marshaler. It will marshal the set into a JSON array of the elements in the set. If the set is empty an empty JSON array is returned.

func (*Locked[M]) NewEmpty added in v0.9.0

func (s *Locked[M]) NewEmpty() Set[M]

NewEmpty returns a new empty set of the same underlying type.

func (*Locked[M]) Pop added in v0.9.0

func (s *Locked[M]) Pop() (M, bool)

Pop removes and returns an element from the set. If the set is empty, it returns the zero value of M and false.

func (*Locked[M]) Remove added in v0.9.0

func (s *Locked[M]) Remove(m M) bool

Remove an element from the set. Returns true if the element was removed, false if it was not present.

func (*Locked[M]) Scan added in v0.10.2

func (s *Locked[M]) Scan(src any) error

Scan implements the sql.Scanner interface. It scans the value from the database into the set. It expects a JSON array of the elements in the set. If the JSON is invalid an error is returned. If the value is nil an empty set is returned.

func (*Locked[M]) String added in v0.9.0

func (s *Locked[M]) String() string

String returns a string representation of the set. It returns a string of the form LockedSet[T](<elements>).

func (*Locked[M]) UnmarshalJSON added in v0.9.0

func (s *Locked[M]) UnmarshalJSON(d []byte) error

UnmarshalJSON implements json.Unmarshaler. It expects a JSON array of the elements in the set. If the set is empty, it returns an empty set. If the JSON is invalid, it returns an error.

func (*Locked[M]) Value added in v0.11.1

func (s *Locked[M]) Value() (driver.Value, error)

Value implements the driver.Valuer interface. It returns the JSON representation of the set.

type LockedOrdered added in v0.9.0

type LockedOrdered[M cmp.Ordered] struct {
	sync.RWMutex
	// contains filtered or unexported fields
}

LockedOrdered is a concurrency safe wrapper around an OrderedSet[M]. It uses a read-write lock to allow multiple readers.

func NewLockedOrdered

func NewLockedOrdered[M cmp.Ordered]() *LockedOrdered[M]

NewLockedOrdered returns an empty *LockedOrdered[M] instance that is safe for concurrent use.

Example
set := NewLockedOrdered[string]()
set.Add("a")
set.Add("b")
set.Add("c")
set.Add("b")
fmt.Println(set.Cardinality())

for i := range set.Iterator {
	fmt.Println(i)
}
Output:

3
a
b
c

func NewLockedOrderedFrom

func NewLockedOrderedFrom[M cmp.Ordered](seq iter.Seq[M]) *LockedOrdered[M]

NewLockedOrderedFrom returns a new *LockedOrdered[M] instance filled with the values from the sequence. The set is safe for concurrent use.

Example
m := []string{"a", "b", "c", "b"}
set := NewLockedOrderedFrom(slices.Values(m))
fmt.Println(set.Cardinality())

for i := range set.Iterator {
	fmt.Println(i)
}
Output:

3
a
b
c

func NewLockedOrderedWith

func NewLockedOrderedWith[M cmp.Ordered](m ...M) *LockedOrdered[M]

NewLockedOrderedWith returns a *LockedOrdered[M] with the values provided.

Example
set := NewLockedOrderedWith("a", "b", "c", "b")
fmt.Println(set.Cardinality())

for i := range set.Iterator {
	fmt.Println(i)
}
Output:

3
a
b
c

func (*LockedOrdered[M]) Add added in v0.9.0

func (s *LockedOrdered[M]) Add(m M) bool

Add an element to the set. Returns true if the element was added, false if it was already present.

func (*LockedOrdered[M]) At added in v0.9.0

func (s *LockedOrdered[M]) At(i int) (M, bool)

At returns the element at the index. If the index is out of bounds, the second return value is false.

func (*LockedOrdered[M]) Backwards added in v0.9.0

func (s *LockedOrdered[M]) Backwards(yield func(int, M) bool)

Backwards iteration yields the index and value of each element in the set in reverse order. It holds a read lock for the duration of iteration. Calling any method that modifies the set while iteration is happening will block until the iteration is complete.

func (*LockedOrdered[M]) Cardinality added in v0.9.0

func (s *LockedOrdered[M]) Cardinality() int

Cardinality returns the number of elements in the set.

func (*LockedOrdered[M]) Clear added in v0.9.0

func (s *LockedOrdered[M]) Clear() int

Clear the set and returns the number of elements removed.

func (*LockedOrdered[M]) Clone added in v0.9.0

func (s *LockedOrdered[M]) Clone() Set[M]

Clone returns a new set of the same underlying type.

func (*LockedOrdered[M]) Contains added in v0.9.0

func (s *LockedOrdered[M]) Contains(m M) bool

Contains returns true if the set contains the element.

func (*LockedOrdered[M]) Index added in v0.9.0

func (s *LockedOrdered[M]) Index(m M) int

Index returns the index of the element in the set, or -1 if not present.

func (*LockedOrdered[M]) Iterator added in v0.9.0

func (s *LockedOrdered[M]) Iterator(yield func(M) bool)

Iterator yields all elements in the set in order. It holds a read lock for the duration of iteration. Calling any method that modifies the set while iteration is happening will block until the iteration is complete.

func (*LockedOrdered[M]) MarshalJSON added in v0.9.0

func (s *LockedOrdered[M]) MarshalJSON() ([]byte, error)

MarshalJSON implements json.Marshaler. It will marshal the set to JSON. It returns a JSON array of the elements in the set. If the set is empty, it returns an empty JSON array.

func (*LockedOrdered[M]) NewEmpty added in v0.9.0

func (s *LockedOrdered[M]) NewEmpty() Set[M]

NewEmpty returns a new empty set of the same underlying type.

func (*LockedOrdered[M]) NewEmptyOrdered added in v0.9.0

func (s *LockedOrdered[M]) NewEmptyOrdered() OrderedSet[M]

NewEmptyOrdered returns a new empty ordered set of the same underlying type.

func (*LockedOrdered[M]) Ordered added in v0.9.0

func (s *LockedOrdered[M]) Ordered(yield func(int, M) bool)

Ordered iteration yields the index and value of each element in the set in order. It holds a read lock for the duration of iteration. Calling any method that modifies the set while iteration is happening will block until the iteration is complete.

func (*LockedOrdered[M]) Pop added in v0.9.0

func (s *LockedOrdered[M]) Pop() (M, bool)

Pop removes and returns an element from the set. If the set is empty, it returns the zero value of M and false.

func (*LockedOrdered[M]) Remove added in v0.9.0

func (s *LockedOrdered[M]) Remove(m M) bool

Remove an element from the set. Returns true if the element was removed, false if it was not present.

func (*LockedOrdered[M]) Scan added in v0.10.2

func (s *LockedOrdered[M]) Scan(src any) error

Scan implements the sql.Scanner interface. It scans the value from the database into the set. It expects a JSON array of the elements in the set. If the JSON is invalid an error is returned. If the value is nil an empty set is returned.

func (*LockedOrdered[M]) Sort added in v0.9.0

func (s *LockedOrdered[M]) Sort()

Sort the set in ascending order.

func (*LockedOrdered[M]) String added in v0.9.0

func (s *LockedOrdered[M]) String() string

String returns a string representation of the set. It returns a string of the form LockedOrderedSet[T](<elements>).

func (*LockedOrdered[M]) UnmarshalJSON added in v0.9.0

func (s *LockedOrdered[M]) UnmarshalJSON(d []byte) error

UnmarshalJSON implements json.Unmarshaler. It expects a JSON array of the elements in the set. If the set is empty, it returns an empty set. If the JSON is invalid, it returns an error.

func (*LockedOrdered[M]) Value added in v0.11.1

func (s *LockedOrdered[M]) Value() (driver.Value, error)

Value implements the driver.Valuer interface. It returns the JSON representation of the set.

type Locker added in v0.10.0

type Locker interface {
	Lock()
	Unlock()
	RLock()
	RUnlock()
}

Locker interface used to determine if a locked implementation is being used.

type Map added in v0.8.0

type Map[M comparable] struct {
	// contains filtered or unexported fields
}

Map is the default set implementation based on top of go's map type. It is not ordered and does not guarantee the order of elements when iterating over them. It is not safe for concurrent use.

func New

func New[M comparable]() *Map[M]

New returns an empty *Map[M] instance.

Example
set := New[string]()
set.Add("a")
set.Add("b")
set.Add("c")
set.Add("b")
fmt.Println(set.Cardinality())
Output:

3

func NewFrom

func NewFrom[M comparable](seq iter.Seq[M]) *Map[M]

NewFrom returns a new *Map[M] filled with the values from the sequence.

Example
m := []string{"a", "b", "c", "b"}
set := NewFrom(slices.Values(m))
fmt.Println(set.Cardinality())
Output:

3

func NewWith added in v0.6.0

func NewWith[M comparable](m ...M) *Map[M]

NewWith returns a new *Map[M] with the values provided.

Example
set := NewWith("a", "b", "c", "b")
fmt.Println(set.Cardinality())
Output:

3

func (*Map[M]) Add added in v0.9.0

func (s *Map[M]) Add(m M) bool

Add an element to the set. Returns true if the element was added, false if it was already present.

func (*Map[M]) Cardinality added in v0.9.0

func (s *Map[M]) Cardinality() int

Cardinality returns the number of elements in the set.

func (*Map[M]) Clear added in v0.9.0

func (s *Map[M]) Clear() int

Clear the set and returns the number of elements removed.

func (*Map[M]) Clone added in v0.9.0

func (s *Map[M]) Clone() Set[M]

Clones the set. Returns a new set of the same underlying type.

func (*Map[M]) Contains added in v0.9.0

func (s *Map[M]) Contains(m M) bool

Contains returns true if the set contains the element.

func (*Map[M]) Iterator added in v0.9.0

func (s *Map[M]) Iterator(yield func(M) bool)

Iterator yields all elements in the set.

func (*Map[M]) MarshalJSON added in v0.9.0

func (s *Map[M]) MarshalJSON() ([]byte, error)

MarshalJSON marshals the set to JSON. It returns a JSON array of the elements in the set. If the set is empty, it returns an empty JSON array.

func (*Map[M]) NewEmpty added in v0.9.0

func (s *Map[M]) NewEmpty() Set[M]

NewEmpty set of the same underlying type.

func (*Map[M]) Pop added in v0.9.0

func (s *Map[M]) Pop() (M, bool)

Pop removes and returns an element from the set. If the set is empty, it returns the zero value of M and false.

func (*Map[M]) Remove added in v0.9.0

func (s *Map[M]) Remove(m M) bool

Remove an element from the set. Returns true if the element was removed, false if it was not present.

func (*Map[M]) Scan added in v0.10.2

func (s *Map[M]) Scan(src any) error

Scan implements the sql.Scanner interface. It scans the value from the database into the set. It expects a JSON array of the elements in the set. If the JSON is invalid an error is returned. If the value is nil an empty set is returned.

func (*Map[M]) String added in v0.9.0

func (s *Map[M]) String() string

String representation of the set. It returns a string of the form Set[T](<elements>).

func (*Map[M]) UnmarshalJSON added in v0.9.0

func (s *Map[M]) UnmarshalJSON(d []byte) error

UnmarshalJSON unmarshals the set from JSON. It expects a JSON array of the elements in the set. If the set is empty, it returns an empty set. If the JSON is invalid, it returns an error.

func (*Map[M]) Value added in v0.11.1

func (s *Map[M]) Value() (driver.Value, error)

Value implements the driver.Valuer interface. It returns the JSON representation of the set.

type Ordered added in v0.9.0

type Ordered[M cmp.Ordered] struct {
	// contains filtered or unexported fields
}

Ordered sets maintains the order that the elements were added in.

func NewOrdered

func NewOrdered[M cmp.Ordered]() *Ordered[M]

NewOrdered returns an empty *Ordered[M].

Example
set := NewOrdered[string]()
set.Add("a")
set.Add("b")
set.Add("c")
set.Add("b")
fmt.Println(set.Cardinality())

for i := range set.Iterator {
	fmt.Println(i)
}
Output:

3
a
b
c

func NewOrderedFrom

func NewOrderedFrom[M cmp.Ordered](seq iter.Seq[M]) *Ordered[M]

NewOrderedFrom returns a new *Ordered[M] filled with the values from the sequence.

Example
m := []string{"a", "b", "c", "b"}
set := NewOrderedFrom(slices.Values(m))
fmt.Println(set.Cardinality())

for i := range set.Iterator {
	fmt.Println(i)
}
Output:

3
a
b
c

func NewOrderedWith added in v0.6.0

func NewOrderedWith[M cmp.Ordered](m ...M) *Ordered[M]

NewOrderedWith returns a new *Ordered[M] with the values provided.

Example
set := NewOrderedWith("a", "b", "c", "b")
fmt.Println(set.Cardinality())

for i := range set.Iterator {
	fmt.Println(i)
}
Output:

3
a
b
c

func (*Ordered[M]) Add added in v0.9.0

func (s *Ordered[M]) Add(m M) bool

Add an element to the set. Returns true if the element was added, false if it was already present. Elements are added to the end of the ordered set.

func (*Ordered[M]) At added in v0.9.0

func (s *Ordered[M]) At(i int) (M, bool)

At returns the element at the index. If the index is out of bounds, the second return value is false.

func (*Ordered[M]) Backwards added in v0.9.0

func (s *Ordered[M]) Backwards(yield func(int, M) bool)

Backwards iteration yields the index and value of each element in the set in reverse order.

func (*Ordered[M]) Cardinality added in v0.9.0

func (s *Ordered[M]) Cardinality() int

Cardinality returns the number of elements in the set.

func (*Ordered[M]) Clear added in v0.9.0

func (s *Ordered[M]) Clear() int

Clear the set and returns the number of elements removed.

func (*Ordered[M]) Clone added in v0.9.0

func (s *Ordered[M]) Clone() Set[M]

Clone returns a copy of the set. The underlying type is the same as the original set.

func (*Ordered[M]) Contains added in v0.9.0

func (s *Ordered[M]) Contains(m M) bool

Contains returns true if the set contains the element.

func (*Ordered[M]) Index added in v0.9.0

func (s *Ordered[M]) Index(m M) int

Index returns the index of the element in the set, or -1 if not present.

func (*Ordered[M]) Iterator added in v0.9.0

func (s *Ordered[M]) Iterator(yield func(M) bool)

Iterator yields all elements in the set in order.

func (*Ordered[M]) MarshalJSON added in v0.9.0

func (s *Ordered[M]) MarshalJSON() ([]byte, error)

MarshalJSON implements json.Marshaler. It will marshal the set into a JSON array of the elements in the set. If the set is empty an empty JSON array is returned.

func (*Ordered[M]) NewEmpty added in v0.9.0

func (s *Ordered[M]) NewEmpty() Set[M]

NewEmpty returns a new empty set of the same underlying type.

func (*Ordered[M]) NewEmptyOrdered added in v0.9.0

func (s *Ordered[M]) NewEmptyOrdered() OrderedSet[M]

NewEmptyOrdered returns a new empty ordered set of the same underlying type.

func (*Ordered[M]) Ordered added in v0.9.0

func (s *Ordered[M]) Ordered(yield func(int, M) bool)

Ordered iteration yields the index and value of each element in the set in order.

func (*Ordered[M]) Pop added in v0.9.0

func (s *Ordered[M]) Pop() (M, bool)

Pop removes and returns an element from the set. If the set is empty, it returns the zero value of M and false.

func (*Ordered[M]) Remove added in v0.9.0

func (s *Ordered[M]) Remove(m M) bool

Remove an element from the set. Returns true if the element was removed, false if it was not present.

func (*Ordered[M]) Scan added in v0.10.2

func (s *Ordered[M]) Scan(src any) error

Scan implements the sql.Scanner interface. It scans the value from the database into the set. It expects a JSON array of the elements in the set. If the JSON is invalid an error is returned. If the value is nil an empty set is returned.

func (*Ordered[M]) Sort added in v0.9.0

func (s *Ordered[M]) Sort()

Sort the set in ascending order.

func (*Ordered[M]) String added in v0.9.0

func (s *Ordered[M]) String() string

String returns a string representation of the set. It returns a string of the form OrderedSet[T](<elements>).

func (*Ordered[M]) UnmarshalJSON added in v0.9.0

func (s *Ordered[M]) UnmarshalJSON(d []byte) error

UnmarshalJSON implements json.Unmarshaler. It expects a JSON array of the elements in the set. If the set is empty, it returns an empty set. If the JSON is invalid, it returns an error.

func (*Ordered[M]) Value added in v0.11.1

func (s *Ordered[M]) Value() (driver.Value, error)

Value implements the driver.Valuer interface. It returns the JSON representation of the set.

type OrderedSet

type OrderedSet[M cmp.Ordered] interface {
	Set[M]

	// Ordered index, value iterator. The yield function is called for each element in the set in order. If the yield
	// function returns false, the iteration is stopped. Changing the set while iterating over it is undefined. It may
	// or may not be safe to change the set or allowed based on the implementation in use. Implementations must document
	// their iteration safety.
	Ordered(yield func(int, M) bool)

	// Backwards index, value iterator. The yield function is called for each element in the set in reverse order. If the
	// yield function returns false, the iteration is stopped. Changing the set while iterating over it is undefined. It
	// may or may not be safe to change the set or allowed based on the implementation in use. Implementations must
	// document their iteration safety.
	Backwards(yield func(int, M) bool)

	// At returns the element at the index. If the index is out of bounds, the second return value is false.
	At(i int) (M, bool)

	// Index returns the index of the element in the set, or -1 if not present.
	Index(M) int

	// Sort the set in ascending order.
	Sort()

	// NewEmptyOrdered returns a new empty ordered set of the same underlying type.
	NewEmptyOrdered() OrderedSet[M]
}

OrderedSet is an extended set interface that implementations can implement to indicate that the set is ordered. OrderedSet sets have a guaranteed order of elements when iterating over them and are restricted to types that are in cmp.Ordered. The order of elements is not guaranteed for sets that do not implement this interface. OrderedSets will always return an ordered set when cloning.

Example
ints := NewOrdered[int]()
ints.Add(5)
ints.Add(3)

// adds 2, 4, 1 in order
AppendSeq(ints, slices.Values([]int{2, 4, 1}))
// adds 6 as it's the only new element
AppendSeq(ints, slices.Values([]int{5, 6, 1}))

// 0,5 1,3 2,2 3,4 4,1 5,6
for idx, i := range ints.Ordered {
	fmt.Println(idx, i)
}

// 5,6 4,1 3,4 2,2 1,3 0,5
for idx, i := range ints.Backwards {
	fmt.Println(idx, i)
}

if v, ok := ints.At(1); v == 3 && ok {
	fmt.Println("3 is at position 1")
}

if ints.Index(3) == 1 {
	fmt.Println("3 is at index 1")
}

if ints.Index(100) == -1 {
	fmt.Println("100 is not present")
}

ints.Sort()
// 1 2 3 4 5 6
for i := range ints.Iterator {
	fmt.Println(i)
}
Output:

0 5
1 3
2 2
3 4
4 1
5 6
5 6
4 1
3 4
2 2
1 3
0 5
3 is at position 1
3 is at index 1
100 is not present
1
2
3
4
5
6

func NewLockedOrderedWrapping added in v0.6.0

func NewLockedOrderedWrapping[M cmp.Ordered](set OrderedSet[M]) OrderedSet[M]

NewLockedOrderedWrapping returns an OrderedSet[M]. If the set is already a locked set, then it is just returned as is. If the set isn't a locked set then the returned set is wrapped so that it is safe for concurrent use.

Example
set := NewOrderedWith("a", "b", "c", "b")

wrapped := NewLockedOrderedWrapping(set)
// wrapped is safe for concurrent use
fmt.Println(wrapped.Cardinality())
Output:

3

func Reverse

func Reverse[K cmp.Ordered](s OrderedSet[K]) OrderedSet[K]

Reverse returns a new OrderedSet with the elements in the reverse order of the original OrderedSet.

Example
ints := NewOrderedWith(2, 3, 5)

reversed := Reverse(ints)
for i := range reversed.Iterator {
	fmt.Println(i)
}
Output:

5
3
2

func Sorted

func Sorted[K cmp.Ordered](s OrderedSet[K]) OrderedSet[K]

Sorted copy of the set. The original set is not modified.

Example
ints := NewOrderedWith(2, 5, 3)

sorted := Sorted(ints)
for i := range sorted.Iterator {
	fmt.Println(i)
}
Output:

2
3
5

type Set

type Set[M comparable] interface {
	// Add an element to the set. Returns true if the element was not already in the set.
	Add(M) bool

	// Cardinality of the set (number of elements in the set).
	Cardinality() int

	// Clear removes all elements from the set and returns the number of elements removed.
	Clear() int

	// Clone returns a copy of the set. Ordered sets maintain their order.
	Clone() Set[M]

	// Contains returns true if the set contains the element.
	Contains(M) bool

	// Iterator for the set elements. The yield function is called for each element in the set. If the yield function
	// returns false, the iteration is stopped. The order of iteration is not guaranteed unless the set is ordered.
	// Changing the set while iterating over it is undefined. It may or may not be safe to change the set or allowed
	// based on the implementation in use. Implementations must document their iteration safety.
	Iterator(yield func(M) bool)

	// NewEmpty returns a new empty set of the same underlying type. If the type is ordered, the new set will also be ordered.
	NewEmpty() Set[M]

	// Pop returns and removes a random element from the set. The second return value is false if nothing was removed.
	Pop() (M, bool)

	// Remove an element from the set. Returns true if the element was in the set.
	Remove(M) bool

	// String representation of the set.
	String() string
}

Set is a collection of unique elements. The elements must be comparable. Each set implementation must implement this interface as the set functions within this package build on top of this interface.

Example
ints := New[int]()
ints.Add(5)
ints.Add(1)
ints.Add(9)

if !ints.Add(1) { // 1 is already present, returns false
	fmt.Println("1 was not added again")
}

if ints.Add(33) { // 33 is not present, returns true
	fmt.Println("33 was added")
}

if ints.Cardinality() == 3 {
	fmt.Println("ints has 3 elements")
}
other := ints.Clone()
if other.Cardinality() == 3 {
	fmt.Println("Cloned set has 3 elements")
}

if ints.Contains(5) {
	fmt.Println("5 is present")
}

if !ints.Contains(2) {
	fmt.Println("2 is not present")
}

if !ints.Remove(2) { // 2 is not present, returns false
	fmt.Println("2 was not removed")
}

if ints.Remove(5) { // 5 is present, returns true
	fmt.Println("5 was removed")
}

if _, ok := ints.Pop(); ok { // 1 || 33 || 9 removed
	// not printing since random
	fmt.Println("Popped a number")
}

if x := ints.Clear(); x == 2 {
	fmt.Println("Clear removed all remaining elements")
}

// Sets aren't ordered, so collect into a slice and sort
// using iterator
items := slices.Collect(other.Iterator)
slices.Sort(items)
for _, i := range items {
	fmt.Println(i)
}

other = ints.NewEmpty()
if other.Cardinality() == 0 {
	fmt.Println("other is empty")
}

other.Add(0)
fmt.Println(other.String())
Output:

1 was not added again
33 was added
5 is present
2 is not present
2 was not removed
5 was removed
Popped a number
Clear removed all remaining elements
1
5
9
33
other is empty
Set[int]([0])

func Difference

func Difference[K comparable](a, b Set[K]) Set[K]

Difference of the two sets. Returns a new set (of the same underlying type as a) with elements that are in the first set but not in the second set.

Example
a := NewWith(5, 3)
b := NewWith(3, 2)

c := Difference(a, b)
out := make([]int, 0, c.Cardinality())
for i := range c.Iterator {
	out = append(out, i)
}
for _, i := range out {
	fmt.Println(i)
}
Output:

5

func Filter added in v0.8.0

func Filter[K comparable](s Set[K], f func(K) bool) Set[K]

Filter applies the function to each element in the set and returns a new set with the elements for which the function returns true.

Example
set := NewWith(3, 0, 1, 2, 4)

filtered := Filter(set, func(i int) bool {
	return i > 2
})
for i := range filtered.Iterator {
	fmt.Println(i)
}
Output:

3
4

func Intersection

func Intersection[K comparable](a, b Set[K]) Set[K]

Intersection of the two sets. Returns a new set (of the same underlying type as a) with elements that are in both sets.

Example
a := NewWith(5, 3)
b := NewWith(3, 2)

c := Intersection(a, b)
out := make([]int, 0, c.Cardinality())
for i := range c.Iterator {
	out = append(out, i)
}
for _, i := range out {
	fmt.Println(i)
}
Output:

3

func MapBy added in v0.9.0

func MapBy[K comparable, V comparable](s Set[K], f func(K) V) Set[V]

MapBy applies the function to each element in the set and returns a new set with the results.

Example
set := NewWith(1, 2, 3)

mapped := MapBy(set, func(i int) int {
	return i * 2
})
for i := range mapped.Iterator {
	fmt.Println(i)
}

mapped2 := MapBy(set, func(i int) string {
	return fmt.Sprintf("%d", i)
})
for i := range mapped2.Iterator {
	fmt.Println(i)
}
Output:

2
4
6
1
2
3

func NewLockedWrapping added in v0.6.0

func NewLockedWrapping[M comparable](set Set[M]) Set[M]

NewLockedWrapping returns a Set[M]. If set is already a locked set, then it is just returned as is. If set isn't a locked set then the returned set is wrapped so that it is safe for concurrent use.

Example
set := NewWith("a", "b", "c", "b")

wrapped := NewLockedWrapping(set)
// wrapped is safe for concurrent use
fmt.Println(wrapped.Cardinality())
Output:

3

func SymmetricDifference

func SymmetricDifference[K comparable](a, b Set[K]) Set[K]

SymmetricDifference of the two sets. Returns a new set (of the same underlying type as a) with elements that are not in both sets.

Example
a := NewWith(5, 3)
b := NewWith(3, 2)

c := SymmetricDifference(a, b)
for i := range c.Iterator {
	fmt.Println(i)
}
Output:

2
5

func Union

func Union[K comparable](a, b Set[K]) Set[K]

Union of the two sets. Returns a new set (of the same underling type as a) with all elements from both sets.

Example
a := NewWith(5, 3)
b := NewWith(3, 2)

c := Union(a, b)
out := make([]int, 0, c.Cardinality())
for i := range c.Iterator {
	out = append(out, i)
}
slices.Sort(out)
for _, i := range out {
	fmt.Println(i)
}
Output:

2
3
5

type SyncMap added in v0.9.0

type SyncMap[M comparable] struct {
	// contains filtered or unexported fields
}

SyncMap is a concurrency safe set type that uses a sync.Map.

func NewSyncMap added in v0.9.0

func NewSyncMap[M comparable]() *SyncMap[M]

NewSyncMap returns an empty Set[M] that is backed by a sync.Map, making it safe for concurrent use. Please read the documentation for sync.Map to understand the behavior of modifying the map.

Example
set := NewSyncMap[string]()
set.Add("a")
set.Add("b")
set.Add("c")
set.Add("b")
fmt.Println(set.Cardinality())
Output:

3

func NewSyncMapFrom added in v0.9.0

func NewSyncMapFrom[M comparable](seq iter.Seq[M]) *SyncMap[M]

NewSyncMapFrom returns a new Set[M] filled with the values from the sequence and is backed by a sync.Map, making it safe for concurrent use. Please read the documentation for sync.Map to understand the behavior of modifying the map.

Example
m := []string{"a", "b", "c", "b"}
set := NewSyncMapFrom(slices.Values(m))
fmt.Println(set.Cardinality())
Output:

3

func NewSyncMapWith added in v0.9.0

func NewSyncMapWith[M comparable](m ...M) *SyncMap[M]

NewSyncMapWith returns a new Set[M] filled with the values provided and is backed by a sync.Map, making it safe for concurrent use. Please read the documentation for sync.Map to understand the behavior of modifying the map.

Example
set := NewSyncMapWith("a", "b", "c", "b")
fmt.Println(set.Cardinality())
Output:

3

func (*SyncMap[M]) Add added in v0.9.0

func (s *SyncMap[M]) Add(m M) bool

func (*SyncMap[M]) Cardinality added in v0.9.0

func (s *SyncMap[M]) Cardinality() int

func (*SyncMap[M]) Clear added in v0.9.0

func (s *SyncMap[M]) Clear() int

func (*SyncMap[M]) Clone added in v0.9.0

func (s *SyncMap[M]) Clone() Set[M]

func (*SyncMap[M]) Contains added in v0.9.0

func (s *SyncMap[M]) Contains(m M) bool

func (*SyncMap[M]) Iterator added in v0.9.0

func (s *SyncMap[M]) Iterator(yield func(M) bool)

Iterator yields all elements in the set. It is safe to call concurrently with other methods, but the order and behavior is undefined, as per sync.Map's `Range`.

func (*SyncMap[M]) MarshalJSON added in v0.9.0

func (s *SyncMap[M]) MarshalJSON() ([]byte, error)

func (*SyncMap[M]) NewEmpty added in v0.9.0

func (s *SyncMap[M]) NewEmpty() Set[M]

func (*SyncMap[M]) Pop added in v0.9.0

func (s *SyncMap[M]) Pop() (M, bool)

func (*SyncMap[M]) Remove added in v0.9.0

func (s *SyncMap[M]) Remove(m M) bool

func (*SyncMap[M]) Scan added in v0.10.2

func (s *SyncMap[M]) Scan(src any) error

Scan implements the sql.Scanner interface. It scans the value from the database into the set. It expects a JSON array of the elements in the set. If the JSON is invalid an error is returned. If the value is nil an empty set is returned.

func (*SyncMap[M]) String added in v0.9.0

func (s *SyncMap[M]) String() string

func (*SyncMap[M]) UnmarshalJSON added in v0.9.0

func (s *SyncMap[M]) UnmarshalJSON(d []byte) error

func (*SyncMap[M]) Value added in v0.11.1

func (s *SyncMap[M]) Value() (driver.Value, error)

Value implements the driver.Valuer interface. It returns the JSON representation of the set.

Jump to

Keyboard shortcuts

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