sets

package module
v1.0.0 Latest Latest
Warning

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

Go to latest
Published: Oct 16, 2025 License: MIT Imports: 3 Imported by: 0

README

Go Sets 🎯

A fast, type-safe, and easy-to-use set library for Go with three flavors to match your needs.

Go Version

Features

Three set types - Choose the behavior you need 🚀 Fast lookups - O(1) membership checks 🔒 Type-safe - Powered by Go generics 🔄 Iterator support - Works with Go 1.23+ range loops 📦 Zero dependencies - Just the Go standard library

Installation

go get github.com/spandigital/sets

Requires Go 1.23 or later for iterator support.

Quick Start

import "github.com/spandigital/sets"

// Create a set
fruits := sets.NewSet("apple", "banana", "cherry")

// Check membership
fruits.Contains("apple")  // true

// Add and remove
fruits.Add("date")
fruits.Remove("banana")

// Iterate
for fruit := range fruits.All() {
    fmt.Println(fruit)
}

Three Types of Sets

1. Set - Fast and Unordered

Perfect when you just need fast lookups and don't care about order.

tags := sets.NewSet("golang", "databases", "web")

tags.Add("api")
tags.Contains("golang")  // true
tags.Len()              // 4

// Order is random
for tag := range tags.All() {
    fmt.Println(tag)  // unpredictable order
}

Use when: Speed is priority and order doesn't matter.

2. OrderedSet - Sorted Values

Returns values in sorted order. Great for consistent output.

scores := sets.NewOrderedSet(95, 87, 92, 88)

for score := range scores.All() {
    fmt.Println(score)  // 87, 88, 92, 95
}

scores.Values()  // [87, 88, 92, 95]

Use when: You need sorted output (leaderboards, alphabetical lists, etc.)

3. InsertionOrderedSet - Preserves Order

Remembers the order you added items. Perfect for maintaining sequences.

steps := sets.NewInsertionOrderedSet("login", "verify", "dashboard")
steps.Add("logout")

for step := range steps.All() {
    fmt.Println(step)  // login, verify, dashboard, logout
}

Use when: Order of insertion matters (workflows, history, etc.)

Common Operations

All set types support the same operations:

s := sets.NewSet(1, 2, 3)

// Basic operations
s.Add(4, 5, 6)           // Add multiple items
s.Remove(2)              // Remove item
s.Contains(3)            // true
s.Len()                  // 5
s.IsEmpty()              // false
s.Clear()                // Remove all

// Set operations
s1 := sets.NewSet(1, 2, 3)
s2 := sets.NewSet(2, 3, 4)

s1.Union(s2)             // {1, 2, 3, 4}
s1.Intersection(s2)      // {2, 3}
s1.Difference(s2)        // {1}
s1.Equal(s2)             // false

Iteration

All sets support Go 1.23+ range-over-function iteration:

colors := sets.NewOrderedSet("red", "green", "blue")

// Standard range loop
for color := range colors.All() {
    fmt.Println(color)
}

// Early termination works
for color := range colors.All() {
    if color == "green" {
        break  // stops iteration
    }
}

// Or get a slice
allColors := colors.Values()  // []string{"blue", "green", "red"}

Performance Characteristics

Operation Set OrderedSet InsertionOrderedSet
Contains O(1) O(1) O(1)
Add O(1) O(1) O(1) amortized
Remove O(1) O(1) O(n)
Values O(n) O(n log n) O(n)
Iteration O(n) O(n log n) O(n)

Examples

Deduplicating a Slice
items := []string{"a", "b", "a", "c", "b"}
unique := sets.NewSet(items...)
fmt.Println(unique.Values())  // [a, b, c] (random order)
Finding Common Elements
alice := sets.NewSet("golang", "python", "rust")
bob := sets.NewSet("python", "javascript", "rust")

common := alice.Intersection(bob)
// common contains: python, rust
Maintaining Order
history := sets.NewInsertionOrderedSet[string]()
history.Add("home")
history.Add("search")
history.Add("profile")
history.Add("search")  // duplicate, ignored

// history.All() yields: home, search, profile

Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

License

[License information here]

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Adder added in v1.0.0

type Adder[T any] interface {
	Add(...T)
}

Adder inserts elements into a collection.

type Clearer added in v1.0.0

type Clearer interface {
	Clear()
}

Clearer removes all elements from a collection.

type Containser added in v1.0.0

type Containser[T any] interface {
	Contains(T) bool
}

Containser checks if an element exists in a collection.

type Differencer added in v1.0.0

type Differencer[T any, S any] interface {
	Difference(S) S
}

Differencer returns elements in one collection but not another.

type EmptyChecker added in v1.0.0

type EmptyChecker interface {
	IsEmpty() bool
}

EmptyChecker determines if a collection is empty.

type Equaler added in v1.0.0

type Equaler[S any] interface {
	Equal(S) bool
}

Equaler compares two collections for equality.

type InsertionOrderedSet added in v1.0.0

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

InsertionOrderedSet is a generic set data structure that preserves insertion order. Unlike Set (unordered) and OrderedSet (sorted), InsertionOrderedSet returns values in the order they were first added. It provides O(1) membership checks but O(n) removal operations. Duplicate values are automatically handled - adding the same value multiple times has no effect beyond the first addition.

func NewInsertionOrderedSet added in v1.0.0

func NewInsertionOrderedSet[T comparable](items ...T) *InsertionOrderedSet[T]

NewInsertionOrderedSet creates a new InsertionOrderedSet with the given initial items. Items are stored in the order provided. Duplicate items are deduplicated while preserving the first occurrence's position.

func (*InsertionOrderedSet[T]) Add added in v1.0.0

func (s *InsertionOrderedSet[T]) Add(items ...T)

Add inserts one or more items into the set. Items are added to the end of the order. Adding items that already exist has no effect. Time complexity: O(m) where m is the number of items to add

func (*InsertionOrderedSet[T]) All added in v1.0.0

func (s *InsertionOrderedSet[T]) All() iter.Seq[T]

All returns an iterator over all elements in the set in insertion order. Elements are yielded in the order they were first added to the set. The iterator can be used with range loops: for v := range set.All() { ... } Time complexity: O(n)

func (*InsertionOrderedSet[T]) Clear added in v1.0.0

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

Clear removes all elements from the set, making it empty. Time complexity: O(1)

func (*InsertionOrderedSet[T]) Contains added in v1.0.0

func (s *InsertionOrderedSet[T]) Contains(t T) bool

Contains checks if the given item exists in the set. Returns true if the item is present, false otherwise. Time complexity: O(1)

func (*InsertionOrderedSet[T]) Difference added in v1.0.0

func (s *InsertionOrderedSet[T]) Difference(other *InsertionOrderedSet[T]) *InsertionOrderedSet[T]

Difference returns a new set containing elements that are in this set but not in the other set. The insertion order from this set is preserved. Time complexity: O(n) where n is the size of this set

func (*InsertionOrderedSet[T]) Equal added in v1.0.0

func (s *InsertionOrderedSet[T]) Equal(other *InsertionOrderedSet[T]) bool

Equal returns true if both sets contain exactly the same elements. Order is not considered for equality - only membership matters. Time complexity: O(n) where n is the size of this set

func (*InsertionOrderedSet[T]) Intersection added in v1.0.0

func (s *InsertionOrderedSet[T]) Intersection(other *InsertionOrderedSet[T]) *InsertionOrderedSet[T]

Intersection returns a new set containing only elements that exist in both sets. The insertion order from this set is preserved for common elements. Time complexity: O(n) where n is the size of this set

func (*InsertionOrderedSet[T]) IsEmpty added in v1.0.0

func (s *InsertionOrderedSet[T]) IsEmpty() bool

IsEmpty returns true if the set contains no elements. Time complexity: O(1)

func (*InsertionOrderedSet[T]) Len added in v1.0.0

func (s *InsertionOrderedSet[T]) Len() int

Len returns the number of elements in the set. Time complexity: O(1)

func (*InsertionOrderedSet[T]) Remove added in v1.0.0

func (s *InsertionOrderedSet[T]) Remove(items ...T)

Remove deletes one or more items from the set. Removing items that don't exist has no effect. Time complexity: O(n*m) where n is set size and m is number of items to remove

func (*InsertionOrderedSet[T]) Union added in v1.0.0

func (s *InsertionOrderedSet[T]) Union(other *InsertionOrderedSet[T]) *InsertionOrderedSet[T]

Union returns a new set containing all elements from both this set and the other set. Elements from this set appear first in insertion order, followed by new elements from the other set in their insertion order. Time complexity: O(n + m) where n and m are the sizes of the two sets

func (*InsertionOrderedSet[T]) Values added in v1.0.0

func (s *InsertionOrderedSet[T]) Values() []T

Values returns all elements in the set as a slice in insertion order. The order reflects the sequence in which elements were first added. Time complexity: O(n)

type Intersectioner added in v1.0.0

type Intersectioner[T any, S any] interface {
	Intersection(S) S
}

Intersectioner returns common elements between two collections.

type Iterable added in v1.0.0

type Iterable[T any] interface {
	All() iter.Seq[T]
}

Iterable provides an iterator over elements in a collection.

type Lener added in v1.0.0

type Lener interface {
	Len() int
}

Lener returns the number of elements in a collection.

type OrderedSet added in v1.0.0

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

OrderedSet is a generic set data structure for ordered types (integers, floats, strings). Unlike Set, OrderedSet returns values in sorted order when calling Values(). It provides O(1) membership checks and efficient set operations. Duplicate values are automatically handled - adding the same value multiple times has no effect beyond the first addition.

func NewOrderedSet

func NewOrderedSet[T cmp.Ordered](items ...T) *OrderedSet[T]

NewOrderedSet creates a new OrderedSet with the given initial items. Duplicate items in the input are automatically deduplicated.

func (*OrderedSet[T]) Add added in v1.0.0

func (s *OrderedSet[T]) Add(items ...T)

Add inserts one or more items into the set. Adding items that already exist has no effect.

func (*OrderedSet[T]) All added in v1.0.0

func (s *OrderedSet[T]) All() iter.Seq[T]

All returns an iterator over all elements in the set in sorted order. Elements are yielded in ascending order. The iterator can be used with range loops: for v := range set.All() { ... }

func (*OrderedSet[T]) Clear added in v1.0.0

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

Clear removes all elements from the set, making it empty.

func (*OrderedSet[T]) Contains added in v1.0.0

func (s *OrderedSet[T]) Contains(t T) (found bool)

Contains checks if the given item exists in the set. Returns true if the item is present, false otherwise.

func (*OrderedSet[T]) Difference added in v1.0.0

func (s *OrderedSet[T]) Difference(other *OrderedSet[T]) *OrderedSet[T]

Difference returns a new set containing elements that are in this set but not in the other set.

func (*OrderedSet[T]) Equal added in v1.0.0

func (s *OrderedSet[T]) Equal(other *OrderedSet[T]) bool

Equal returns true if both sets contain exactly the same elements.

func (*OrderedSet[T]) Intersection added in v1.0.0

func (s *OrderedSet[T]) Intersection(other *OrderedSet[T]) *OrderedSet[T]

Intersection returns a new set containing only elements that exist in both sets.

func (*OrderedSet[T]) IsEmpty added in v1.0.0

func (s *OrderedSet[T]) IsEmpty() bool

IsEmpty returns true if the set contains no elements.

func (*OrderedSet[T]) Len added in v1.0.0

func (s *OrderedSet[T]) Len() int

Len returns the number of elements in the set.

func (*OrderedSet[T]) Remove added in v1.0.0

func (s *OrderedSet[T]) Remove(items ...T)

Remove deletes one or more items from the set. Removing items that don't exist has no effect.

func (*OrderedSet[T]) Union added in v1.0.0

func (s *OrderedSet[T]) Union(other *OrderedSet[T]) *OrderedSet[T]

Union returns a new set containing all elements from both this set and the other set.

func (*OrderedSet[T]) Values added in v1.0.0

func (s *OrderedSet[T]) Values() []T

Values returns all elements in the set as a sorted slice. Elements are sorted in ascending order.

type Remover added in v1.0.0

type Remover[T any] interface {
	Remove(...T)
}

Remover deletes elements from a collection.

type Set

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

Set is a generic unordered set data structure for any comparable type. It provides O(1) membership checks and efficient set operations. Duplicate values are automatically handled - adding the same value multiple times has no effect beyond the first addition.

func NewSet

func NewSet[T comparable](items ...T) *Set[T]

NewSet creates a new Set with the given initial items. Duplicate items in the input are automatically deduplicated.

func (*Set[T]) Add added in v1.0.0

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

Add inserts one or more items into the set. Adding items that already exist has no effect.

func (*Set[T]) All added in v1.0.0

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

All returns an iterator over all elements in the set. The iteration order is not guaranteed and may vary between calls. The iterator can be used with range loops: for v := range set.All() { ... }

func (*Set[T]) Clear added in v1.0.0

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

Clear removes all elements from the set, making it empty.

func (*Set[T]) Contains

func (s *Set[T]) Contains(t T) (found bool)

Contains checks if the given item exists in the set. Returns true if the item is present, false otherwise.

func (*Set[T]) Difference added in v1.0.0

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

Difference returns a new set containing elements that are in this set but not in the other set.

func (*Set[T]) Equal added in v1.0.0

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

Equal returns true if both sets contain exactly the same elements.

func (*Set[T]) Intersection added in v1.0.0

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

Intersection returns a new set containing only elements that exist in both sets.

func (*Set[T]) IsEmpty added in v1.0.0

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

IsEmpty returns true if the set contains no elements.

func (*Set[T]) Len added in v1.0.0

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

Len returns the number of elements in the set.

func (*Set[T]) Remove added in v1.0.0

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

Remove deletes one or more items from the set. Removing items that don't exist has no effect.

func (*Set[T]) Union added in v1.0.0

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

Union returns a new set containing all elements from both this set and the other set.

func (*Set[T]) Values

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

Values returns all elements in the set as a slice. The order of elements is not guaranteed and may vary between calls.

type Unioner added in v1.0.0

type Unioner[T any, S any] interface {
	Union(S) S
}

Unioner combines two collections into a new one.

type Valuer added in v1.0.0

type Valuer[T any] interface {
	Values() []T
}

Valuer returns all elements from a collection.

Jump to

Keyboard shortcuts

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