Documentation
¶
Overview ¶
Package keyed provides a generic Set for elements that are identified by a key rather than by their own value.
Use it when the element type is not comparable (it contains slices or maps), or when only part of an element decides whether two elements are the same, such as a record's ID. A key function maps each element to a comparable key, and two elements are the same element exactly when their keys are equal:
byEmail := keyed.New(func(u User) string { return u.Email })
Because key equality is element equality, adding an element whose key is already present replaces the element stored under that key.
A Set is not safe for concurrent use. SyncSet, created with NewSync, is the same set behind a lock, for goroutines that share it.
If your elements are already comparable and you want whole-value equality, use the github.com/kastolars/readyset package instead.
Index ¶
- func Sorted[K cmp.Ordered, V any](s Set[K, V]) []V
- type Set
- func (s Set[K, V]) Add(elements ...V)
- func (s Set[K, V]) AddSet(other Set[K, V])
- func (s Set[K, V]) All() iter.Seq[V]
- func (s Set[K, V]) Clear()
- func (s Set[K, V]) Clone() Set[K, V]
- func (s Set[K, V]) Contains(e V) bool
- func (s Set[K, V]) ContainsAll(elements ...V) bool
- func (s Set[K, V]) ContainsAny(elements ...V) bool
- func (s Set[K, V]) ContainsKey(key K) bool
- func (s Set[K, V]) Difference(other Set[K, V]) Set[K, V]
- func (s Set[K, V]) Equal(other Set[K, V]) bool
- func (s Set[K, V]) Filter(keep func(V) bool) Set[K, V]
- func (s Set[K, V]) Get(key K) (V, bool)
- func (s Set[K, V]) Intersection(other Set[K, V]) Set[K, V]
- func (s Set[K, V]) IsDisjoint(other Set[K, V]) bool
- func (s Set[K, V]) IsEmpty() bool
- func (s Set[K, V]) IsProperSubset(other Set[K, V]) bool
- func (s Set[K, V]) IsProperSuperset(other Set[K, V]) bool
- func (s Set[K, V]) IsSubset(other Set[K, V]) bool
- func (s Set[K, V]) IsSuperset(other Set[K, V]) bool
- func (s Set[K, V]) Keys() []K
- func (s Set[K, V]) Len() int
- func (s Set[K, V]) MarshalJSON() ([]byte, error)
- func (s Set[K, V]) Pop() (V, bool)
- func (s Set[K, V]) Remove(elements ...V)
- func (s Set[K, V]) RemoveFunc(remove func(V) bool) int
- func (s Set[K, V]) RemoveKey(keys ...K)
- func (s Set[K, V]) RemoveSet(other Set[K, V])
- func (s Set[K, V]) RetainSet(other Set[K, V])
- func (s Set[K, V]) Slice() []V
- func (s Set[K, V]) String() string
- func (s Set[K, V]) SymmetricDifference(other Set[K, V]) Set[K, V]
- func (s Set[K, V]) Union(other Set[K, V]) Set[K, V]
- func (s *Set[K, V]) UnmarshalJSON(data []byte) error
- type SyncSet
- func (s *SyncSet[K, V]) Add(elements ...V)
- func (s *SyncSet[K, V]) AddSet(other *SyncSet[K, V])
- func (s *SyncSet[K, V]) All() iter.Seq[V]
- func (s *SyncSet[K, V]) Clear()
- func (s *SyncSet[K, V]) Clone() *SyncSet[K, V]
- func (s *SyncSet[K, V]) Contains(e V) bool
- func (s *SyncSet[K, V]) ContainsAll(elements ...V) bool
- func (s *SyncSet[K, V]) ContainsAny(elements ...V) bool
- func (s *SyncSet[K, V]) ContainsKey(key K) bool
- func (s *SyncSet[K, V]) Difference(other *SyncSet[K, V]) *SyncSet[K, V]
- func (s *SyncSet[K, V]) Do(fn func(Set[K, V]))
- func (s *SyncSet[K, V]) Equal(other *SyncSet[K, V]) bool
- func (s *SyncSet[K, V]) Filter(keep func(V) bool) *SyncSet[K, V]
- func (s *SyncSet[K, V]) Get(key K) (V, bool)
- func (s *SyncSet[K, V]) Intersection(other *SyncSet[K, V]) *SyncSet[K, V]
- func (s *SyncSet[K, V]) IsDisjoint(other *SyncSet[K, V]) bool
- func (s *SyncSet[K, V]) IsEmpty() bool
- func (s *SyncSet[K, V]) IsProperSubset(other *SyncSet[K, V]) bool
- func (s *SyncSet[K, V]) IsProperSuperset(other *SyncSet[K, V]) bool
- func (s *SyncSet[K, V]) IsSubset(other *SyncSet[K, V]) bool
- func (s *SyncSet[K, V]) IsSuperset(other *SyncSet[K, V]) bool
- func (s *SyncSet[K, V]) Keys() []K
- func (s *SyncSet[K, V]) Len() int
- func (s *SyncSet[K, V]) MarshalJSON() ([]byte, error)
- func (s *SyncSet[K, V]) Pop() (V, bool)
- func (s *SyncSet[K, V]) Remove(elements ...V)
- func (s *SyncSet[K, V]) RemoveFunc(remove func(V) bool) int
- func (s *SyncSet[K, V]) RemoveKey(keys ...K)
- func (s *SyncSet[K, V]) RemoveSet(other *SyncSet[K, V])
- func (s *SyncSet[K, V]) RetainSet(other *SyncSet[K, V])
- func (s *SyncSet[K, V]) Slice() []V
- func (s *SyncSet[K, V]) Snapshot() Set[K, V]
- func (s *SyncSet[K, V]) String() string
- func (s *SyncSet[K, V]) SymmetricDifference(other *SyncSet[K, V]) *SyncSet[K, V]
- func (s *SyncSet[K, V]) Union(other *SyncSet[K, V]) *SyncSet[K, V]
- func (s *SyncSet[K, V]) UnmarshalJSON(data []byte) error
Examples ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func Sorted ¶ added in v0.2.0
Sorted returns the elements of s as a new slice in ascending order of their keys. It works when the key type is ordered: integers, floats and strings.
Sorted is a function rather than a method because only an ordered key type can be sorted, and a method cannot add that constraint to Set.
Example ¶
users := keyed.New(byEmail,
User{Email: "c@x.io", Name: "Cy"},
User{Email: "a@x.io", Name: "Ann"},
User{Email: "b@x.io", Name: "Bob"},
)
// Elements come back in ascending order of their keys (the emails).
for _, u := range keyed.Sorted(users) {
fmt.Println(u.Name)
}
Output: Ann Bob Cy
Types ¶
type Set ¶
type Set[K comparable, V any] struct { // contains filtered or unexported fields }
Set is an unordered collection of elements with unique keys.
A Set must be created with New; the zero value cannot add, remove or look up elements. Copying a Set copies a reference to the same underlying storage; use Set.Clone for an independent copy.
Operations between two sets compare keys only, so both sets must use the same key function. A set produced by an operation uses the key function of the receiver.
A Set is not safe for concurrent use; use a SyncSet to share one between goroutines.
func Collect ¶ added in v0.3.0
func Collect[K comparable, V any](key func(V) K, seq iter.Seq[V]) Set[K, V]
Collect returns a new set, identified by key, of the elements yielded by seq. As with New, if several elements share a key the last one wins, and Collect panics if key is nil.
Example ¶
rows := []User{
{Email: "a@x.io", Name: "Ann"},
{Email: "b@x.io", Name: "Bob"},
{Email: "a@x.io", Name: "Ann Lee"}, // same key: the last one wins
}
users := keyed.Collect(byEmail, slices.Values(rows))
fmt.Println(names(users))
Output: [Ann Lee Bob]
func New ¶
func New[K comparable, V any](key func(V) K, elements ...V) Set[K, V]
New returns a Set that identifies elements with key, containing elements. If several elements share a key, the last one wins. New panics if key is nil.
Example ¶
package main
import (
"fmt"
"github.com/kastolars/readyset/keyed"
)
// User is the element type used by the examples. Its Tags field makes it
// non-comparable, so it could not be a member of a readyset.Set.
type User struct {
Email string
Name string
Tags []string
}
// byEmail identifies a User by their email address.
func byEmail(u User) string { return u.Email }
func main() {
users := keyed.New(byEmail,
User{Email: "a@x.io", Name: "Ann"},
User{Email: "b@x.io", Name: "Bob"},
)
fmt.Println(users.Len(), users.Contains(User{Email: "a@x.io"}))
}
Output: 2 true
func (Set[K, V]) Add ¶
func (s Set[K, V]) Add(elements ...V)
Add inserts elements into the set. An element whose key is already present replaces the element stored under that key. An element whose key is not equal to itself, such as a NaN, is ignored: the set could never find or remove it.
Example ¶
Elements with equal keys are the same element, so adding one replaces the other.
package main
import (
"fmt"
"github.com/kastolars/readyset/keyed"
)
// User is the element type used by the examples. Its Tags field makes it
// non-comparable, so it could not be a member of a readyset.Set.
type User struct {
Email string
Name string
Tags []string
}
// byEmail identifies a User by their email address.
func byEmail(u User) string { return u.Email }
func main() {
users := keyed.New(byEmail, User{Email: "a@x.io", Name: "Ann"})
users.Add(User{Email: "a@x.io", Name: "Ann Lee"})
u, _ := users.Get("a@x.io")
fmt.Println(users.Len(), u.Name)
}
Output: 1 Ann Lee
func (Set[K, V]) AddSet ¶ added in v0.2.0
AddSet inserts every element of other into the set. For a key present in both sets the element from other replaces the one in s, exactly as if each had been passed to Set.Add. This differs from Set.Union, which keeps the receiver's element. Both sets must use the same key function.
Example ¶
AddSet behaves like Add for every element of the argument, so for a key in both sets the argument's element replaces the existing one.
package main
import (
"fmt"
"sort"
"github.com/kastolars/readyset/keyed"
)
// User is the element type used by the examples. Its Tags field makes it
// non-comparable, so it could not be a member of a readyset.Set.
type User struct {
Email string
Name string
Tags []string
}
// byEmail identifies a User by their email address.
func byEmail(u User) string { return u.Email }
func names(s keyed.Set[string, User]) []string {
out := []string{}
for _, u := range s.Slice() {
out = append(out, u.Name)
}
sort.Strings(out)
return out
}
func main() {
team := keyed.New(byEmail, User{Email: "a@x.io", Name: "Ann"})
joiners := keyed.New(byEmail,
User{Email: "a@x.io", Name: "Ann Lee"},
User{Email: "b@x.io", Name: "Bob"},
)
team.AddSet(joiners)
fmt.Println(names(team))
}
Output: [Ann Lee Bob]
func (Set[K, V]) All ¶
All returns an iterator over the elements of the set, in no particular order.
The set must not be modified while iterating over it.
func (Set[K, V]) Contains ¶
Contains reports whether the set holds an element with the same key as e.
func (Set[K, V]) ContainsAll ¶ added in v0.3.0
ContainsAll reports whether the set holds an element with the same key as each of elements. It is true when elements is empty.
Example ¶
package main
import (
"fmt"
"github.com/kastolars/readyset/keyed"
)
// User is the element type used by the examples. Its Tags field makes it
// non-comparable, so it could not be a member of a readyset.Set.
type User struct {
Email string
Name string
Tags []string
}
// byEmail identifies a User by their email address.
func byEmail(u User) string { return u.Email }
func main() {
team := keyed.New(byEmail,
User{Email: "a@x.io", Name: "Ann"},
User{Email: "b@x.io", Name: "Bob"},
)
// Only the key matters, so a User carrying just an email is enough.
fmt.Println(team.ContainsAll(User{Email: "a@x.io"}, User{Email: "b@x.io"}))
fmt.Println(team.ContainsAny(User{Email: "z@x.io"}))
}
Output: true false
func (Set[K, V]) ContainsAny ¶ added in v0.3.0
ContainsAny reports whether the set holds an element with the same key as at least one of elements. It is false when elements is empty.
func (Set[K, V]) ContainsKey ¶
ContainsKey reports whether the set holds an element stored under key.
func (Set[K, V]) Difference ¶
Difference returns a new set of the keys that are in s but not in other.
Example ¶
package main
import (
"fmt"
"sort"
"github.com/kastolars/readyset/keyed"
)
// User is the element type used by the examples. Its Tags field makes it
// non-comparable, so it could not be a member of a readyset.Set.
type User struct {
Email string
Name string
Tags []string
}
// byEmail identifies a User by their email address.
func byEmail(u User) string { return u.Email }
func names(s keyed.Set[string, User]) []string {
out := []string{}
for _, u := range s.Slice() {
out = append(out, u.Name)
}
sort.Strings(out)
return out
}
func main() {
staff := keyed.New(byEmail,
User{Email: "a@x.io", Name: "Ann"},
User{Email: "b@x.io", Name: "Bob"},
)
admins := keyed.New(byEmail, User{Email: "b@x.io"})
fmt.Println(names(staff.Difference(admins)))
}
Output: [Ann]
func (Set[K, V]) Filter ¶ added in v0.3.0
Filter returns a new set of the elements for which keep returns true. It uses the key function of s.
Example ¶
package main
import (
"fmt"
"sort"
"github.com/kastolars/readyset/keyed"
)
// User is the element type used by the examples. Its Tags field makes it
// non-comparable, so it could not be a member of a readyset.Set.
type User struct {
Email string
Name string
Tags []string
}
// byEmail identifies a User by their email address.
func byEmail(u User) string { return u.Email }
func names(s keyed.Set[string, User]) []string {
out := []string{}
for _, u := range s.Slice() {
out = append(out, u.Name)
}
sort.Strings(out)
return out
}
func main() {
team := keyed.New(byEmail,
User{Email: "a@x.io", Name: "Ann", Tags: []string{"admin"}},
User{Email: "b@x.io", Name: "Bob"},
)
admins := team.Filter(func(u User) bool { return len(u.Tags) > 0 })
fmt.Println(names(admins))
}
Output: [Ann]
func (Set[K, V]) Get ¶
Get returns the element stored under key. The boolean reports whether key was present; if it was not, the element is the zero value of V.
func (Set[K, V]) Intersection ¶
Intersection returns a new set of the keys that are in both s and other. The elements come from s.
Example ¶
package main
import (
"fmt"
"sort"
"github.com/kastolars/readyset/keyed"
)
// User is the element type used by the examples. Its Tags field makes it
// non-comparable, so it could not be a member of a readyset.Set.
type User struct {
Email string
Name string
Tags []string
}
// byEmail identifies a User by their email address.
func byEmail(u User) string { return u.Email }
func names(s keyed.Set[string, User]) []string {
out := []string{}
for _, u := range s.Slice() {
out = append(out, u.Name)
}
sort.Strings(out)
return out
}
func main() {
staff := keyed.New(byEmail,
User{Email: "a@x.io", Name: "Ann"},
User{Email: "b@x.io", Name: "Bob"},
)
admins := keyed.New(byEmail,
User{Email: "b@x.io", Name: "Bob (admin)"},
User{Email: "c@x.io", Name: "Cy"},
)
fmt.Println(names(staff.Intersection(admins)))
}
Output: [Bob]
func (Set[K, V]) IsDisjoint ¶
IsDisjoint reports whether s and other have no keys in common.
func (Set[K, V]) IsProperSubset ¶ added in v0.3.0
IsProperSubset reports whether s is a subset of other and the two are not equal, that is, other has at least one key that s lacks.
func (Set[K, V]) IsProperSuperset ¶ added in v0.3.0
IsProperSuperset reports whether s is a superset of other and the two are not equal, that is, s has at least one key that other lacks.
func (Set[K, V]) IsSuperset ¶
IsSuperset reports whether every key of other is also in s.
func (Set[K, V]) Keys ¶
func (s Set[K, V]) Keys() []K
Keys returns the keys of the elements in the set as a new slice, in no particular order. The order can differ between calls.
func (Set[K, V]) MarshalJSON ¶
MarshalJSON implements json.Marshaler. It encodes the set as a JSON array of its elements, ordered by key, so a set encodes the same way whatever its map iteration order. An empty set encodes as [].
Example ¶
package main
import (
"encoding/json"
"fmt"
"github.com/kastolars/readyset/keyed"
)
// User is the element type used by the examples. Its Tags field makes it
// non-comparable, so it could not be a member of a readyset.Set.
type User struct {
Email string
Name string
Tags []string
}
// byEmail identifies a User by their email address.
func byEmail(u User) string { return u.Email }
func main() {
users := keyed.New(byEmail,
User{Email: "b@x.io", Name: "Bob"},
User{Email: "a@x.io", Name: "Ann"},
)
b, _ := json.Marshal(users)
fmt.Println(string(b))
}
Output: [{"Email":"a@x.io","Name":"Ann","Tags":null},{"Email":"b@x.io","Name":"Bob","Tags":null}]
func (Set[K, V]) Pop ¶ added in v0.3.0
Pop removes and returns an arbitrary element of the set. The boolean is false if the set was empty. Which element is returned is unspecified and can differ between calls, so use it to drain a worklist, not to pick a particular element.
func (Set[K, V]) Remove ¶
func (s Set[K, V]) Remove(elements ...V)
Remove deletes the elements stored under the keys of elements. Keys not present are ignored.
func (Set[K, V]) RemoveFunc ¶ added in v0.3.0
RemoveFunc deletes every element for which remove returns true and reports how many it deleted. remove must not modify the set.
func (Set[K, V]) RemoveKey ¶
func (s Set[K, V]) RemoveKey(keys ...K)
RemoveKey deletes the elements stored under keys. Keys not present are ignored. Unlike Set.Remove it needs no element, so removing an element you only know the key of does not require building one.
Example ¶
package main
import (
"fmt"
"github.com/kastolars/readyset/keyed"
)
// User is the element type used by the examples. Its Tags field makes it
// non-comparable, so it could not be a member of a readyset.Set.
type User struct {
Email string
Name string
Tags []string
}
// byEmail identifies a User by their email address.
func byEmail(u User) string { return u.Email }
func main() {
users := keyed.New(byEmail,
User{Email: "a@x.io", Name: "Ann"},
User{Email: "b@x.io", Name: "Bob"},
)
// Remove by key alone, without building a User.
users.RemoveKey("a@x.io")
fmt.Println(users.Len(), users.ContainsKey("a@x.io"), users.ContainsKey("b@x.io"))
}
Output: 1 false true
func (Set[K, V]) RemoveSet ¶ added in v0.2.0
RemoveSet deletes the elements stored under the keys of other. It is the in-place counterpart of Set.Difference: afterwards s holds what s.Difference(other) would have returned, and other is not modified.
Example ¶
package main
import (
"fmt"
"sort"
"github.com/kastolars/readyset/keyed"
)
// User is the element type used by the examples. Its Tags field makes it
// non-comparable, so it could not be a member of a readyset.Set.
type User struct {
Email string
Name string
Tags []string
}
// byEmail identifies a User by their email address.
func byEmail(u User) string { return u.Email }
func names(s keyed.Set[string, User]) []string {
out := []string{}
for _, u := range s.Slice() {
out = append(out, u.Name)
}
sort.Strings(out)
return out
}
func main() {
team := keyed.New(byEmail,
User{Email: "a@x.io", Name: "Ann"},
User{Email: "b@x.io", Name: "Bob"},
)
leavers := keyed.New(byEmail, User{Email: "b@x.io"})
team.RemoveSet(leavers)
fmt.Println(names(team))
}
Output: [Ann]
func (Set[K, V]) RetainSet ¶ added in v0.3.0
RetainSet deletes the elements whose keys are not also in other. It is the in-place counterpart of Set.Intersection: afterwards s holds what s.Intersection(other) would have returned, and other is not modified.
Example ¶
package main
import (
"fmt"
"sort"
"github.com/kastolars/readyset/keyed"
)
// User is the element type used by the examples. Its Tags field makes it
// non-comparable, so it could not be a member of a readyset.Set.
type User struct {
Email string
Name string
Tags []string
}
// byEmail identifies a User by their email address.
func byEmail(u User) string { return u.Email }
func names(s keyed.Set[string, User]) []string {
out := []string{}
for _, u := range s.Slice() {
out = append(out, u.Name)
}
sort.Strings(out)
return out
}
func main() {
team := keyed.New(byEmail,
User{Email: "a@x.io", Name: "Ann"},
User{Email: "b@x.io", Name: "Bob"},
)
active := keyed.New(byEmail, User{Email: "b@x.io"})
team.RetainSet(active)
fmt.Println(names(team))
}
Output: [Bob]
func (Set[K, V]) Slice ¶
func (s Set[K, V]) Slice() []V
Slice returns the elements of the set as a new slice, in no particular order. The order can differ between calls.
func (Set[K, V]) String ¶
String returns the elements in braces, separated by commas, ordered by key: numeric keys numerically, string keys lexically, and any other key by its printed form. It implements fmt.Stringer.
Example ¶
package main
import (
"fmt"
"github.com/kastolars/readyset/keyed"
)
// User is the element type used by the examples. Its Tags field makes it
// non-comparable, so it could not be a member of a readyset.Set.
type User struct {
Email string
Name string
Tags []string
}
// byEmail identifies a User by their email address.
func byEmail(u User) string { return u.Email }
func main() {
users := keyed.New(byEmail,
User{Email: "b@x.io", Name: "Bob"},
User{Email: "a@x.io", Name: "Ann"},
)
// Elements print in key order.
fmt.Println(users)
}
Output: {{a@x.io Ann []}, {b@x.io Bob []}}
func (Set[K, V]) SymmetricDifference ¶
SymmetricDifference returns a new set of the keys that are in exactly one of s and other.
func (Set[K, V]) Union ¶
Union returns a new set of the keys that are in s, in other, or in both. For a key in both, the element from s is kept.
Example ¶
package main
import (
"fmt"
"sort"
"github.com/kastolars/readyset/keyed"
)
// User is the element type used by the examples. Its Tags field makes it
// non-comparable, so it could not be a member of a readyset.Set.
type User struct {
Email string
Name string
Tags []string
}
// byEmail identifies a User by their email address.
func byEmail(u User) string { return u.Email }
func names(s keyed.Set[string, User]) []string {
out := []string{}
for _, u := range s.Slice() {
out = append(out, u.Name)
}
sort.Strings(out)
return out
}
func main() {
staff := keyed.New(byEmail,
User{Email: "a@x.io", Name: "Ann"},
User{Email: "b@x.io", Name: "Bob"},
)
admins := keyed.New(byEmail,
User{Email: "b@x.io", Name: "Bob (admin)"},
User{Email: "c@x.io", Name: "Cy"},
)
// For a key in both sets, the receiver's element is kept.
fmt.Println(names(staff.Union(admins)))
}
Output: [Ann Bob Cy]
func (*Set[K, V]) UnmarshalJSON ¶
UnmarshalJSON implements json.Unmarshaler. It decodes a JSON array into the set, replacing its previous contents; if several elements share a key, the last one wins. A JSON null leaves the set unchanged. If decoding fails the set is also left unchanged, including when a key function returns a value that cannot be a map key.
The set needs a key function to decode, so it must have been created with New. To decode into a struct field, initialise the field first:
cfg := Config{Users: keyed.New(func(u User) string { return u.Email })}
err := json.Unmarshal(data, &cfg)
Decoding into the zero value returns an error.
Example ¶
package main
import (
"encoding/json"
"fmt"
"github.com/kastolars/readyset/keyed"
)
// User is the element type used by the examples. Its Tags field makes it
// non-comparable, so it could not be a member of a readyset.Set.
type User struct {
Email string
Name string
Tags []string
}
// byEmail identifies a User by their email address.
func byEmail(u User) string { return u.Email }
func main() {
type Config struct {
Users keyed.Set[string, User] `json:"users"`
}
// The set needs its key function to decode, so create it with New first.
cfg := Config{Users: keyed.New(byEmail)}
err := json.Unmarshal([]byte(`{"users":[{"Email":"a@x.io","Name":"Ann"}]}`), &cfg)
fmt.Println(err, cfg.Users.Len())
}
Output: <nil> 1
type SyncSet ¶ added in v0.4.0
type SyncSet[K comparable, V any] struct { // contains filtered or unexported fields }
SyncSet is a Set that is safe for concurrent use by multiple goroutines.
Use it when goroutines share a set and you want the locking done for you. A plain Set is faster and has no restrictions, so prefer it when only one goroutine touches the set at a time, or when you already hold a lock of your own around it.
A SyncSet must be created with NewSync; like a Set, the zero value cannot add, remove or look up elements. It contains a lock, so it must be used through a pointer and must not be copied after first use; go vet reports copies.
Every method is atomic by itself, but a sequence of calls is not. This is a race, because another goroutine can add the key between the two calls:
if !s.ContainsKey(k) { // wrong
s.Add(v)
}
Use SyncSet.Do to run several steps under one lock.
Operations that take another SyncSet lock both sets, always in the same order, so two goroutines running a.Union(b) and b.Union(a) cannot deadlock, and a.Union(a) is fine. Functions you pass in (to SyncSet.Filter, SyncSet.RemoveFunc and SyncSet.Do) run while the lock is held, so they must not call methods on any SyncSet, not only the same one. A callback that locks a different set does so outside that fixed order, so two callbacks that each use the other's set can deadlock. To combine two sets use a two-set method such as SyncSet.RemoveSet or SyncSet.Intersection, or take a SyncSet.Snapshot of the other set before the call.
The lock protects the set, not what its elements point to. Elements are copied by value into snapshots, clones and slices, and anything an element holds a reference to, such as a pointer, a slice or a map, is shared and not locked.
func NewSync ¶ added in v0.4.0
func NewSync[K comparable, V any](key func(V) K, elements ...V) *SyncSet[K, V]
NewSync returns a SyncSet that identifies elements with key, containing elements. If several elements share a key, the last one wins. NewSync panics if key is nil.
func (*SyncSet[K, V]) Add ¶ added in v0.4.0
func (s *SyncSet[K, V]) Add(elements ...V)
Add inserts elements into the set. An element whose key is already present replaces the element stored under that key.
func (*SyncSet[K, V]) AddSet ¶ added in v0.4.0
AddSet inserts every element of other into the set. For a key present in both sets the element from other replaces the one in s. See Set.AddSet.
func (*SyncSet[K, V]) All ¶ added in v0.4.0
All returns an iterator over the elements of the set, in no particular order. The elements are copied when iteration starts, so the loop body may freely change this set (or any other goroutine may) without affecting or deadlocking the loop, and the loop does not see those changes.
func (*SyncSet[K, V]) Clear ¶ added in v0.4.0
func (s *SyncSet[K, V]) Clear()
Clear removes every element from the set.
func (*SyncSet[K, V]) Contains ¶ added in v0.4.0
Contains reports whether the set holds an element with the same key as e.
func (*SyncSet[K, V]) ContainsAll ¶ added in v0.4.0
ContainsAll reports whether the set holds an element with the same key as each of elements. It is true when elements is empty.
func (*SyncSet[K, V]) ContainsAny ¶ added in v0.4.0
ContainsAny reports whether the set holds an element with the same key as at least one of elements. It is false when elements is empty.
func (*SyncSet[K, V]) ContainsKey ¶ added in v0.4.0
ContainsKey reports whether the set holds an element stored under key.
func (*SyncSet[K, V]) Difference ¶ added in v0.4.0
Difference returns a new set of the keys that are in s but not in other.
func (*SyncSet[K, V]) Do ¶ added in v0.4.0
Do calls fn with the underlying Set while holding the set's write lock, and returns when fn returns. Use it for a sequence of steps that must not be interleaved with other goroutines, such as adding an element only if its key is absent:
var added bool
users.Do(func(set keyed.Set[string, User]) {
if !set.ContainsKey(u.Email) {
set.Add(u)
added = true
}
})
fn must not call methods on s, which would deadlock, or on any other SyncSet, which can deadlock too (see SyncSet), and must not keep the Set after it returns.
Example ¶
Checking for a key and then adding is a race, because another goroutine can add the key in between. Do runs both steps under one lock.
users := keyed.NewSync(byEmail, User{Email: "a@x.io", Name: "Ann"})
register := func(u User) bool {
registered := false
users.Do(func(set keyed.Set[string, User]) {
if !set.ContainsKey(u.Email) {
set.Add(u)
registered = true
}
})
return registered
}
fmt.Println(register(User{Email: "a@x.io", Name: "Impostor"}), register(User{Email: "b@x.io", Name: "Bob"}))
fmt.Println(names(users.Snapshot()))
Output: false true [Ann Bob]
func (*SyncSet[K, V]) Equal ¶ added in v0.4.0
Equal reports whether s and other contain the same keys.
func (*SyncSet[K, V]) Filter ¶ added in v0.4.0
Filter returns a new set of the elements for which keep returns true. It uses the key function of s. keep runs while the set is locked, so it must not call methods on any SyncSet.
func (*SyncSet[K, V]) Get ¶ added in v0.4.0
Get returns the element stored under key. The boolean reports whether key was present; if it was not, the element is the zero value of V.
func (*SyncSet[K, V]) Intersection ¶ added in v0.4.0
Intersection returns a new set of the keys that are in both s and other. The elements come from s.
func (*SyncSet[K, V]) IsDisjoint ¶ added in v0.4.0
IsDisjoint reports whether s and other have no keys in common.
func (*SyncSet[K, V]) IsProperSubset ¶ added in v0.4.0
IsProperSubset reports whether s is a subset of other and the two are not equal.
func (*SyncSet[K, V]) IsProperSuperset ¶ added in v0.4.0
IsProperSuperset reports whether s is a superset of other and the two are not equal.
func (*SyncSet[K, V]) IsSubset ¶ added in v0.4.0
IsSubset reports whether every key of s is also in other.
func (*SyncSet[K, V]) IsSuperset ¶ added in v0.4.0
IsSuperset reports whether every key of other is also in s.
func (*SyncSet[K, V]) Keys ¶ added in v0.4.0
func (s *SyncSet[K, V]) Keys() []K
Keys returns the keys of the elements in the set as a new slice, in no particular order.
func (*SyncSet[K, V]) MarshalJSON ¶ added in v0.4.0
MarshalJSON encodes the set as a JSON array ordered by key. See Set.MarshalJSON.
func (*SyncSet[K, V]) Pop ¶ added in v0.4.0
Pop removes and returns an arbitrary element of the set. The boolean is false if the set was empty. See Set.Pop.
func (*SyncSet[K, V]) Remove ¶ added in v0.4.0
func (s *SyncSet[K, V]) Remove(elements ...V)
Remove deletes the elements stored under the keys of elements. Keys not present are ignored.
func (*SyncSet[K, V]) RemoveFunc ¶ added in v0.4.0
RemoveFunc deletes every element for which remove returns true and reports how many it deleted. remove runs while the set is locked, so it must not call methods on any SyncSet.
func (*SyncSet[K, V]) RemoveKey ¶ added in v0.4.0
func (s *SyncSet[K, V]) RemoveKey(keys ...K)
RemoveKey deletes the elements stored under keys. Keys not present are ignored.
func (*SyncSet[K, V]) RemoveSet ¶ added in v0.4.0
RemoveSet deletes the elements stored under the keys of other. It is the in-place counterpart of SyncSet.Difference, and other is not modified.
func (*SyncSet[K, V]) RetainSet ¶ added in v0.4.0
RetainSet deletes the elements whose keys are not also in other. It is the in-place counterpart of SyncSet.Intersection, and other is not modified.
func (*SyncSet[K, V]) Slice ¶ added in v0.4.0
func (s *SyncSet[K, V]) Slice() []V
Slice returns the elements of the set as a new slice, in no particular order. The order can differ between calls.
func (*SyncSet[K, V]) Snapshot ¶ added in v0.4.0
Snapshot returns the elements as a plain, independent Set, for use with Sorted or in code that does not need locking. Later changes to either set do not affect the other. The elements themselves are copied by value, so anything they refer to is still shared.
func (*SyncSet[K, V]) String ¶ added in v0.4.0
String returns the elements in braces, ordered by key. See Set.String.
func (*SyncSet[K, V]) SymmetricDifference ¶ added in v0.4.0
SymmetricDifference returns a new set of the keys that are in exactly one of s and other.
func (*SyncSet[K, V]) Union ¶ added in v0.4.0
Union returns a new set of the keys that are in s, in other, or in both. For a key in both, the element from s is kept.
func (*SyncSet[K, V]) UnmarshalJSON ¶ added in v0.4.0
UnmarshalJSON decodes a JSON array into the set. The set must have been created with NewSync, because it needs its key function. See Set.UnmarshalJSON.