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.
If your elements are already comparable and you want whole-value equality, use the github.com/kastolars/readyset package instead.
Index ¶
- type Set
- func (s Set[K, V]) Add(elements ...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]) 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]) 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]) 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]) Remove(elements ...V)
- func (s Set[K, V]) RemoveKey(keys ...K)
- 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
Examples ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
This section is empty.
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.
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.
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]) All ¶
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[K, V]) Contains ¶
Contains reports whether the set holds an element with the same key as e.
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]) 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]) 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 equal sets always encode to the same bytes. 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]) 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]) 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]) 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.
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