set

package
v7.0.101 Latest Latest
Warning

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

Go to latest
Published: May 1, 2026 License: Apache-2.0 Imports: 7 Imported by: 0

Documentation

Overview

Example

Example demonstrates basic usage of generic Set with integers

package main

import (
	"fmt"

	"github.com/libreFS/librefs-go/v7/pkg/set"
)

func main() {
	// Create a new set of integers
	s := set.Create(1, 2, 3, 4, 5)

	// Add an element
	s.Add(6)

	// Check if element exists
	fmt.Println("Contains 3:", s.Contains(3))
	fmt.Println("Contains 10:", s.Contains(10))

	// Remove an element
	s.Remove(2)

	// Get sorted slice
	fmt.Println("Elements:", set.ToSliceOrdered(s))

}
Output:
Contains 3: true
Contains 10: false
Elements: [1 3 4 5 6]

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func ToSliceOrdered

func ToSliceOrdered[T cmp.Ordered](set Set[T]) []T

ToSliceOrdered - returns Set as a sorted slice for ordered types. This is a convenience method for types that implement cmp.Ordered. The result is deterministic and always sorted in ascending order.

Example

ExampleToSliceOrdered demonstrates sorting different ordered types

package main

import (
	"fmt"

	"github.com/libreFS/librefs-go/v7/pkg/set"
)

func main() {
	// Works with any ordered type (int, float, string, etc.)
	ints := set.Create(5, 2, 8, 1, 9)
	fmt.Println("Sorted ints:", set.ToSliceOrdered(ints))

	strings := set.Create("zebra", "apple", "mango", "banana")
	fmt.Println("Sorted strings:", set.ToSliceOrdered(strings))

	floats := set.Create(3.14, 2.71, 1.41, 1.73)
	fmt.Println("Sorted floats:", set.ToSliceOrdered(floats))

}
Output:
Sorted ints: [1 2 5 8 9]
Sorted strings: [apple banana mango zebra]
Sorted floats: [1.41 1.73 2.71 3.14]

Types

type IntSet

type IntSet Set[int]

IntSet - uses map as set of ints. This is now implemented using the generic Set[int] type.

func CopyIntSet

func CopyIntSet(set IntSet) IntSet

CopyIntSet - returns copy of given set.

func CreateIntSet

func CreateIntSet(il ...int) IntSet

CreateIntSet - creates new int set with given int values.

func NewIntSet

func NewIntSet() IntSet

NewIntSet - creates new int set.

func (IntSet) Add

func (set IntSet) Add(i int)

Add - adds int to the set.

func (IntSet) AppendBinary

func (s IntSet) AppendBinary(b []byte) ([]byte, error)

AppendBinary appends the binary representation of itself to the end of b

func (IntSet) ApplyFunc

func (set IntSet) ApplyFunc(applyFn func(int) int) IntSet

ApplyFunc - returns new set containing each value processed by 'applyFn'. A 'applyFn' should accept element in a set as a argument and return a processed int. The function can do any logic to return a processed int.

func (IntSet) Contains

func (set IntSet) Contains(i int) bool

Contains - checks if int is in the set.

func (*IntSet) DecodeMsg

func (s *IntSet) DecodeMsg(reader *msgp.Reader) error

DecodeMsg decodes the message from the reader.

func (IntSet) Difference

func (set IntSet) Difference(iset IntSet) IntSet

Difference - returns the difference with given set as new set.

func (IntSet) EncodeMsg

func (s IntSet) EncodeMsg(writer *msgp.Writer) error

EncodeMsg encodes the message to the writer. Values are stored as a slice of ints or nil.

func (IntSet) Equals

func (set IntSet) Equals(iset IntSet) bool

Equals - checks whether given set is equal to current set or not.

func (IntSet) FuncMatch

func (set IntSet) FuncMatch(matchFn func(int, int) bool, matchInt int) IntSet

FuncMatch - returns new set containing each value who passes match function. A 'matchFn' should accept element in a set as first argument and 'matchInt' as second argument. The function can do any logic to compare both the arguments and should return true to accept element in a set to include in output set else the element is ignored.

func (IntSet) Intersection

func (set IntSet) Intersection(iset IntSet) IntSet

Intersection - returns the intersection with given set as new set.

func (IntSet) IsEmpty

func (set IntSet) IsEmpty() bool

IsEmpty - returns whether the set is empty or not.

func (IntSet) MarshalBinary

func (s IntSet) MarshalBinary() ([]byte, error)

MarshalBinary encodes the receiver into a binary form and returns the result.

func (IntSet) MarshalJSON

func (set IntSet) MarshalJSON() ([]byte, error)

MarshalJSON - converts to JSON data.

func (IntSet) MarshalMsg

func (s IntSet) MarshalMsg(bytes []byte) ([]byte, error)

MarshalMsg encodes the message to the bytes. Values are stored as a slice of ints or nil.

func (IntSet) Msgsize

func (s IntSet) Msgsize() int

Msgsize returns the maximum size of the message.

func (IntSet) Remove

func (set IntSet) Remove(i int)

Remove - removes int in the set. It does nothing if int does not exist in the set.

func (IntSet) String

func (set IntSet) String() string

String - returns printable string of the set.

func (IntSet) ToSlice

func (set IntSet) ToSlice() []int

ToSlice - returns IntSet as int slice.

func (IntSet) Union

func (set IntSet) Union(iset IntSet) IntSet

Union - returns the union with given set as new set.

func (*IntSet) UnmarshalBinary

func (s *IntSet) UnmarshalBinary(b []byte) error

UnmarshalBinary decodes the binary representation of itself from b

func (*IntSet) UnmarshalJSON

func (set *IntSet) UnmarshalJSON(data []byte) error

UnmarshalJSON - parses JSON data and creates new set with it.

func (*IntSet) UnmarshalMsg

func (s *IntSet) UnmarshalMsg(bytes []byte) ([]byte, error)

UnmarshalMsg decodes the message from the bytes.

type Set

type Set[T comparable] map[T]struct{}

Set - uses map as a set of comparable elements.

Important Caveats:

  • Sets are unordered by nature. Map iteration order is non-deterministic in Go.
  • When converting to slices, use ToSlice() with a comparison function or ToSliceOrdered() for ordered types to get deterministic, sorted results.
  • Comparison functions must provide total ordering: if your comparison returns 0 for different elements, their relative order in the result is undefined.
  • For deterministic ordering when elements may compare equal, use secondary sort criteria (e.g., sort by length first, then alphabetically for ties).
Example (ComplexCustomType)

ExampleSet_complexCustomType demonstrates using Set with a complex comparable struct

package main

import (
	"fmt"

	"github.com/libreFS/librefs-go/v7/pkg/set"
)

func main() {
	// Define a complex type representing a network connection
	type Connection struct {
		Host     string
		Port     int
		Protocol string
		Secure   bool
	}

	// Track unique connections
	connections := set.New[Connection]()

	// Add connections
	connections.Add(Connection{"api.example.com", 443, "https", true})
	connections.Add(Connection{"db.example.com", 5432, "postgres", true})
	connections.Add(Connection{"api.example.com", 443, "https", true}) // duplicate
	connections.Add(Connection{"cache.example.com", 6379, "redis", false})

	fmt.Println("Unique connections:", len(connections))

	// Check if specific connection exists
	apiConn := Connection{"api.example.com", 443, "https", true}
	fmt.Println("Has API connection:", connections.Contains(apiConn))

	// Filter secure connections
	secureConns := connections.FuncMatch(func(conn, _ Connection) bool {
		return conn.Secure
	}, Connection{})

	fmt.Println("Secure connections:", len(secureConns))

}
Output:
Unique connections: 3
Has API connection: true
Secure connections: 2
Example (CustomType)

ExampleSet_customType demonstrates using Set with custom types

package main

import (
	"fmt"

	"github.com/libreFS/librefs-go/v7/pkg/set"
)

func main() {
	type UserID int

	activeUsers := set.Create(UserID(101), UserID(102), UserID(103))
	premiumUsers := set.Create(UserID(102), UserID(103), UserID(104))

	// Find users that are both active and premium
	activePremium := activeUsers.Intersection(premiumUsers)
	fmt.Println("Active premium users:", set.ToSliceOrdered(activePremium))

	// Find active users that are not premium
	freeUsers := activeUsers.Difference(premiumUsers)
	fmt.Println("Free users:", set.ToSliceOrdered(freeUsers))

}
Output:
Active premium users: [102 103]
Free users: [101]
Example (Float64Set)

ExampleSet_float64Set demonstrates using Set with floating point numbers

package main

import (
	"fmt"

	"github.com/libreFS/librefs-go/v7/pkg/set"
)

func main() {
	temps := set.Create(98.6, 100.4, 99.1, 98.6)

	fmt.Println("Unique temperatures:", len(temps))
	fmt.Println("Has 100.4:", temps.Contains(100.4))
	fmt.Println("Temperatures:", set.ToSliceOrdered(temps))

}
Output:
Unique temperatures: 3
Has 100.4: true
Temperatures: [98.6 99.1 100.4]
Example (IntSet)

ExampleSet_intSet demonstrates set operations with integers

package main

import (
	"fmt"

	"github.com/libreFS/librefs-go/v7/pkg/set"
)

func main() {
	setA := set.Create(1, 2, 3, 4)
	setB := set.Create(3, 4, 5, 6)

	// Union
	union := setA.Union(setB)
	fmt.Println("Union:", set.ToSliceOrdered(union))

	// Intersection
	intersection := setA.Intersection(setB)
	fmt.Println("Intersection:", set.ToSliceOrdered(intersection))

	// Difference
	difference := setA.Difference(setB)
	fmt.Println("Difference:", set.ToSliceOrdered(difference))

}
Output:
Union: [1 2 3 4 5 6]
Intersection: [3 4]
Difference: [1 2]
Example (NestedComparable)

ExampleSet_nestedComparable demonstrates using Set with nested comparable structs

package main

import (
	"fmt"

	"github.com/libreFS/librefs-go/v7/pkg/set"
)

func main() {
	// Define nested comparable types
	type Coordinate struct {
		Lat, Lon float64
	}

	type Location struct {
		Name   string
		Coords Coordinate
	}

	places := set.New[Location]()

	places.Add(Location{"Eiffel Tower", Coordinate{48.8584, 2.2945}})
	places.Add(Location{"Statue of Liberty", Coordinate{40.6892, -74.0445}})
	places.Add(Location{"Eiffel Tower", Coordinate{48.8584, 2.2945}}) // duplicate

	fmt.Println("Unique places:", len(places))

	// Check if location exists
	eiffel := Location{"Eiffel Tower", Coordinate{48.8584, 2.2945}}
	fmt.Println("Has Eiffel Tower:", places.Contains(eiffel))

}
Output:
Unique places: 2
Has Eiffel Tower: true
Example (StringSet)

ExampleSet_stringSet demonstrates using generic Set with strings

package main

import (
	"fmt"

	"github.com/libreFS/librefs-go/v7/pkg/set"
)

func main() {
	fruits := set.Create("apple", "banana", "cherry")

	fruits.Add("date")
	fruits.Add("banana") // duplicate, won't be added

	fmt.Println("Has apple:", fruits.Contains("apple"))
	fmt.Println("Count:", len(fruits))
	fmt.Println("Fruits:", set.ToSliceOrdered(fruits))

}
Output:
Has apple: true
Count: 4
Fruits: [apple banana cherry date]
Example (StructWithMultipleFields)

ExampleSet_structWithMultipleFields demonstrates deduplication with complex structs

package main

import (
	"fmt"

	"github.com/libreFS/librefs-go/v7/pkg/set"
)

func main() {
	// Define a struct representing an S3 object key with metadata
	type S3Object struct {
		Bucket  string
		Key     string
		Version string
		ETag    string
	}

	objects := set.New[S3Object]()

	// Add objects
	objects.Add(S3Object{"my-bucket", "docs/file1.txt", "v1", "abc123"})
	objects.Add(S3Object{"my-bucket", "docs/file2.txt", "v1", "def456"})
	objects.Add(S3Object{"my-bucket", "docs/file1.txt", "v2", "ghi789"})
	objects.Add(S3Object{"my-bucket", "docs/file1.txt", "v1", "abc123"}) // duplicate

	fmt.Println("Unique objects:", len(objects))

	// Check for specific object
	obj := S3Object{"my-bucket", "docs/file1.txt", "v1", "abc123"}
	fmt.Println("Contains object:", objects.Contains(obj))

	// Get all objects from a specific bucket
	bucketObjects := objects.FuncMatch(func(o, filter S3Object) bool {
		return o.Bucket == filter.Bucket && o.Key == filter.Key
	}, S3Object{Bucket: "my-bucket", Key: "docs/file1.txt"})

	fmt.Println("Versions of file1.txt:", len(bucketObjects))

}
Output:
Unique objects: 3
Contains object: true
Versions of file1.txt: 2

func Copy

func Copy[T comparable](set Set[T]) Set[T]

Copy - returns copy of given set.

Example

ExampleCopy demonstrates copying a set

package main

import (
	"fmt"

	"github.com/libreFS/librefs-go/v7/pkg/set"
)

func main() {
	original := set.Create(1, 2, 3)
	copied := set.Copy(original)

	// Modify the copy
	copied.Add(4)
	copied.Remove(1)

	fmt.Println("Original:", set.ToSliceOrdered(original))
	fmt.Println("Modified copy:", set.ToSliceOrdered(copied))

}
Output:
Original: [1 2 3]
Modified copy: [2 3 4]

func Create

func Create[T comparable](sl ...T) Set[T]

Create - creates new set with given values.

Example

ExampleCreate demonstrates creating a set with initial values

package main

import (
	"fmt"

	"github.com/libreFS/librefs-go/v7/pkg/set"
)

func main() {
	// Create set with initial values
	primes := set.Create(2, 3, 5, 7, 11, 13)

	fmt.Println("Is 7 prime:", primes.Contains(7))
	fmt.Println("Is 9 prime:", primes.Contains(9))
	fmt.Println("Prime count:", len(primes))

}
Output:
Is 7 prime: true
Is 9 prime: false
Prime count: 6

func New

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

New - creates new set.

Example

ExampleNew demonstrates creating an empty set and adding elements

package main

import (
	"fmt"

	"github.com/libreFS/librefs-go/v7/pkg/set"
)

func main() {
	// Create an empty set of strings
	tags := set.New[string]()

	// Add elements one by one
	tags.Add("go")
	tags.Add("generics")
	tags.Add("set")
	tags.Add("go") // duplicate, ignored

	fmt.Println("Tags:", set.ToSliceOrdered(tags))
	fmt.Println("Count:", len(tags))

}
Output:
Tags: [generics go set]
Count: 3

func (Set[T]) Add

func (set Set[T]) Add(s T)

Add - adds element to the set.

func (Set[T]) ApplyFunc

func (set Set[T]) ApplyFunc(applyFn func(T) T) Set[T]

ApplyFunc - returns new set containing each value processed by 'applyFn'. A 'applyFn' should accept element in a set as an argument and return a processed value. The function can do any logic to return a processed value.

Example

ExampleSet_ApplyFunc demonstrates transforming set elements

package main

import (
	"fmt"

	"github.com/libreFS/librefs-go/v7/pkg/set"
)

func main() {
	numbers := set.Create(1, 2, 3, 4, 5)

	// Square each number
	squared := numbers.ApplyFunc(func(n int) int {
		return n * n
	})

	fmt.Println("Original:", set.ToSliceOrdered(numbers))
	fmt.Println("Squared:", set.ToSliceOrdered(squared))

}
Output:
Original: [1 2 3 4 5]
Squared: [1 4 9 16 25]

func (Set[T]) Contains

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

Contains - checks if element is in the set.

func (Set[T]) Difference

func (set Set[T]) Difference(sset Set[T]) Set[T]

Difference - returns the difference with given set as new set.

func (Set[T]) Equals

func (set Set[T]) Equals(sset Set[T]) bool

Equals - checks whether given set is equal to current set or not.

Example

ExampleSet_Equals demonstrates checking set equality

package main

import (
	"fmt"

	"github.com/libreFS/librefs-go/v7/pkg/set"
)

func main() {
	set1 := set.Create(1, 2, 3)
	set2 := set.Create(3, 2, 1) // same elements, different order
	set3 := set.Create(1, 2, 3, 4)

	fmt.Println("set1 equals set2:", set1.Equals(set2))
	fmt.Println("set1 equals set3:", set1.Equals(set3))

}
Output:
set1 equals set2: true
set1 equals set3: false

func (Set[T]) FuncMatch

func (set Set[T]) FuncMatch(matchFn func(T, T) bool, matchValue T) Set[T]

FuncMatch - returns new set containing each value that passes match function. A 'matchFn' should accept element in a set as first argument and 'matchValue' as second argument. The function can do any logic to compare both the arguments and should return true to accept element in a set to include in output set else the element is ignored.

Example

ExampleSet_FuncMatch demonstrates filtering set elements

package main

import (
	"fmt"

	"github.com/libreFS/librefs-go/v7/pkg/set"
)

func main() {
	numbers := set.Create(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)

	// Find all even numbers
	evens := numbers.FuncMatch(func(n, _ int) bool {
		return n%2 == 0
	}, 0)

	// Find all numbers greater than 5
	greaterThanFive := numbers.FuncMatch(func(n, threshold int) bool {
		return n > threshold
	}, 5)

	fmt.Println("Even numbers:", set.ToSliceOrdered(evens))
	fmt.Println("Greater than 5:", set.ToSliceOrdered(greaterThanFive))

}
Output:
Even numbers: [2 4 6 8 10]
Greater than 5: [6 7 8 9 10]

func (Set[T]) Intersection

func (set Set[T]) Intersection(sset Set[T]) Set[T]

Intersection - returns the intersection with given set as new set.

func (Set[T]) IsEmpty

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

IsEmpty - returns whether the set is empty or not.

func (Set[T]) Remove

func (set Set[T]) Remove(s T)

Remove - removes element from the set. It does nothing if element does not exist in the set.

func (Set[T]) ToSlice

func (set Set[T]) ToSlice(cmpFn func(a, b T) int) []T

ToSlice - returns Set as a slice sorted using the provided comparison function. If cmpFn is nil, the slice order is undefined (non-deterministic).

Important: The comparison function should provide total ordering. If it returns 0 for elements that are not identical, their relative order in the result is undefined. For deterministic results, use secondary sort criteria for tie-breaking.

Example

ExampleSet_ToSlice demonstrates custom sorting with comparison function

package main

import (
	"fmt"

	"github.com/libreFS/librefs-go/v7/pkg/set"
)

func main() {
	words := set.Create("go", "rust", "python", "javascript")

	// Sort by length (shortest first)
	byLength := words.ToSlice(func(a, b string) int {
		return len(a) - len(b)
	})

	fmt.Println("By length:", byLength)

}
Output:
By length: [go rust python javascript]

func (Set[T]) Union

func (set Set[T]) Union(sset Set[T]) Set[T]

Union - returns the union with given set as new set.

type StringSet

type StringSet Set[string]

StringSet - uses map as set of strings. This is now implemented using the generic Set[string] type.

func CopyStringSet

func CopyStringSet(set StringSet) StringSet

CopyStringSet - returns copy of given set.

func CreateStringSet

func CreateStringSet(sl ...string) StringSet

CreateStringSet - creates new string set with given string values.

func NewStringSet

func NewStringSet() StringSet

NewStringSet - creates new string set.

func (StringSet) Add

func (set StringSet) Add(s string)

Add - adds string to the set.

func (StringSet) AppendBinary

func (s StringSet) AppendBinary(b []byte) ([]byte, error)

AppendBinary appends the binary representation of itself to the end of b

func (StringSet) ApplyFunc

func (set StringSet) ApplyFunc(applyFn func(string) string) StringSet

ApplyFunc - returns new set containing each value processed by 'applyFn'. A 'applyFn' should accept element in a set as a argument and return a processed string. The function can do any logic to return a processed string.

func (StringSet) Contains

func (set StringSet) Contains(s string) bool

Contains - checks if string is in the set.

func (*StringSet) DecodeMsg

func (s *StringSet) DecodeMsg(reader *msgp.Reader) error

DecodeMsg decodes the message from the reader.

func (StringSet) Difference

func (set StringSet) Difference(sset StringSet) StringSet

Difference - returns the difference with given set as new set.

func (StringSet) EncodeMsg

func (s StringSet) EncodeMsg(writer *msgp.Writer) error

EncodeMsg encodes the message to the writer. Values are stored as a slice of strings or nil.

func (StringSet) Equals

func (set StringSet) Equals(sset StringSet) bool

Equals - checks whether given set is equal to current set or not.

func (StringSet) FuncMatch

func (set StringSet) FuncMatch(matchFn func(string, string) bool, matchString string) StringSet

FuncMatch - returns new set containing each value who passes match function. A 'matchFn' should accept element in a set as first argument and 'matchString' as second argument. The function can do any logic to compare both the arguments and should return true to accept element in a set to include in output set else the element is ignored.

func (StringSet) Intersection

func (set StringSet) Intersection(sset StringSet) StringSet

Intersection - returns the intersection with given set as new set.

func (StringSet) IsEmpty

func (set StringSet) IsEmpty() bool

IsEmpty - returns whether the set is empty or not.

func (StringSet) MarshalBinary

func (s StringSet) MarshalBinary() ([]byte, error)

MarshalBinary encodes the receiver into a binary form and returns the result.

func (StringSet) MarshalJSON

func (set StringSet) MarshalJSON() ([]byte, error)

MarshalJSON - converts to JSON data.

func (StringSet) MarshalMsg

func (s StringSet) MarshalMsg(bytes []byte) ([]byte, error)

MarshalMsg encodes the message to the bytes. Values are stored as a slice of strings or nil.

func (StringSet) Msgsize

func (s StringSet) Msgsize() int

Msgsize returns the maximum size of the message.

func (StringSet) Remove

func (set StringSet) Remove(s string)

Remove - removes string in the set. It does nothing if string does not exist in the set.

func (StringSet) String

func (set StringSet) String() string

String - returns printable string of the set.

func (StringSet) ToByteSlices

func (set StringSet) ToByteSlices() [][]byte

ToByteSlices - returns StringSet as a sorted slice of byte slices, using only one allocation.

func (StringSet) ToSlice

func (set StringSet) ToSlice() []string

ToSlice - returns StringSet as string slice.

func (StringSet) Union

func (set StringSet) Union(sset StringSet) StringSet

Union - returns the union with given set as new set.

func (*StringSet) UnmarshalBinary

func (s *StringSet) UnmarshalBinary(b []byte) error

UnmarshalBinary decodes the binary representation of itself from b

func (*StringSet) UnmarshalJSON

func (set *StringSet) UnmarshalJSON(data []byte) error

UnmarshalJSON - parses JSON data and creates new set with it.

func (*StringSet) UnmarshalMsg

func (s *StringSet) UnmarshalMsg(bytes []byte) ([]byte, error)

UnmarshalMsg decodes the message from the bytes.

Jump to

Keyboard shortcuts

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