container

package
v0.9.0 Latest Latest
Warning

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

Go to latest
Published: Jun 13, 2025 License: MIT Imports: 3 Imported by: 0

Documentation

Overview

Package container provides core interfaces and utilities for working with data structures.

It defines the base Container interface for all container types, along with utility functions for sorting and manipulating container elements. The package integrates with standard Go libraries and supports generic types for flexibility and type safety.

Key features:

  • Container: Base interface for all data structures.
  • Iterators: Stateful iteration (defined separately).
  • Enumerable: Ruby-inspired container functions (defined separately).
  • Serialization: JSON marshalers and unmarshalers (defined separately).

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func GetSortedValues

func GetSortedValues[T cmp.Ordered](c Container[T]) []T

GetSortedValues returns a sorted slice of the container's elements for ordered types.

It uses the natural ordering of type T, as defined by the cmp.Ordered constraint. The original container remains unchanged, and the returned slice is a new copy.

Returns the original values slice if it has fewer than 2 elements, as sorting is unnecessary.

func GetSortedValuesFunc

func GetSortedValuesFunc[T any](c Container[T], cmp cmp.Comparator[T]) []T

GetSortedValuesFunc returns a sorted slice of the container's elements using a custom comparator.

It is designed for types that do not implement cmp.Ordered, allowing flexible sorting logic via the provided comparator function. The original container remains unchanged.

Returns the original values slice if it has fewer than 2 elements, as sorting is unnecessary.

Types

type BiMap added in v0.9.0

type BiMap[K comparable, V comparable] interface {
	Map[K, V]

	// GetKey retrieves the key associated with the specified value.
	// Returns the key and true if the value was found, or the zero value of K
	// and false if the value was not present.
	GetKey(val V) (key K, found bool)

	// HasValue returns true if the map contains the value.
	HasValue(val V) bool

	// DeleteValue removes the key-value pair associated with the specified value.
	// Returns the key and true if the value was found and removed, false if the value was not present.
	DeleteValue(val V) (key K, found bool)
}

BiMap is a generic interface for bidirectional maps, extending the Map interface to support lookups by both keys and values. In a bidirectional map, both keys and values are unique, allowing values to map back to their corresponding keys.

Type parameter K must be comparable for key equality checks. Type parameter V must also be comparable to ensure value uniqueness and lookup capability.

BiMap inherits all Map operations and adds methods specific to bidirectional functionality. Implementations must maintain the invariant that each value is associated with exactly one key, just as each key is associated with exactly one value.

type Container

type Container[T any] interface {
	// Clear removes all elements from the container, resetting it to an empty state.
	Clear()

	// IsEmpty returns true if the container has no elements.
	IsEmpty() bool

	// Len returns the number of elements in the container.
	Len() int

	// String returns a string representation of the container's elements,
	// suitable for logging or debugging.
	String() string

	// ToSlice returns a slice containing all elements in the container.
	// The order of elements is implementation-dependent.
	ToSlice() []T
}

Container defines the fundamental interface for all container data structures.

This interface provides basic operations for querying and manipulating a container's elements, using a generic type T to support any data type.

Example usage:

type IntList []int
func (l IntList) Empty() bool { return len(l) == 0 }
func (l IntList) Len() int { return len(l) }
func (l IntList) Clear() { l = nil }
func (l IntList) Values() []int { return l }
func (l IntList) String() string { return fmt.Sprint(l) }

type Deque added in v0.2.3

type Deque[T comparable] interface {
	Container[T]

	// PushFront adds an element to the front of the deque.
	PushFront(val T)

	// PushBack adds an element to the back of the deque.
	PushBack(val T)

	// PopFront removes and returns the front element of the deque.
	// Returns the element and true if the deque is non-empty,
	// or the zero value of T and false if the deque is empty.
	PopFront() (val T, ok bool)

	// PopBack removes and returns the back element of the deque.
	// Returns the element and true if the deque is non-empty,
	// or the zero value of T and false if the deque is empty.
	PopBack() (val T, ok bool)

	// Front returns the front element of the deque without removing it.
	// Returns the element and true if the deque is non-empty,
	// or the zero value of T and false if the deque is empty.
	Front() (val T, ok bool)

	// Back returns the back element of the deque without removing it.
	// Returns the element and true if the deque is non-empty,
	// or the zero value of T and false if the deque is empty.
	Back() (val T, ok bool)

	// Capacity returns the maximum number of elements the deque can hold,
	// or -1 if the capacity is unbounded (e.g., for linked-list implementations).
	Capacity() int

	// Get returns the element at the specified index, where 0 is the front.
	// Returns the element and true if the index is valid,
	// or the zero value of T and false if the index is out of bounds.
	Get(idx int) (val T, ok bool)

	// Set updates the element at the specified index, where 0 is the front.
	// Panics if the index is out of bounds.
	Set(idx int, val T)

	// Insert adds an element at the specified index, shifting subsequent elements.
	// Index 0 inserts at the front, and Len() inserts at the back.
	// Panics if the index is out of bounds (i.e., idx < 0 or idx > Len()).
	Insert(idx int, val T)

	// Remove removes the element at the specified index, shifting subsequent elements.
	// Panics if the index is out of bounds.
	Remove(idx int) (val T, ok bool)

	// Swap exchanges the elements at the specified indices.
	// Panics if either index is out of bounds.
	Swap(idx1, idx2 int)
}

Deque is a generic interface for a double-ended queue, allowing addition and removal of elements at both the front and back. Implementations (e.g., circular buffers, doubly-linked lists) must support all operations defined here, including those inherited from Container[T] (e.g., Len, IsEmpty, Clear). Type parameter T must be comparable to enable equality checks for elements.

type Map added in v0.2.0

type Map[K comparable, V any] interface {
	Container[V]

	// Put associates the specified value with the given key in the map.
	// If the key already exists, its value is updated with the new value.
	// If the key does not exist, a new key-value pair is added.
	Put(key K, val V)

	// Get retrieves the value associated with the specified key.
	// Returns the value and true if the key was found, or the zero value of V
	// and false if the key was not present.
	Get(key K) (val V, found bool)

	// Has returns true if the specified key is present in the map, false otherwise.
	Has(key K) bool

	// Delete removes the key-value pair associated with the specified key.
	// Returns the key, value, and true if the key was found and removed, false if the key was not present.
	Delete(key K) (val V, found bool)

	// Keys returns a slice containing all keys in the map.
	// The order of keys matches the map's ordering (e.g., sorted for tree maps).
	// Returns an empty slice if the map is empty.
	Keys() []K

	// Values returns a slice containing all values in the map.
	// The order of values corresponds to the order of keys in the map's ordering.
	// Returns an empty slice if the map is empty.
	Values() []V

	// Entries returns two slices containing all keys and values in the map,
	// respectively, in the map's ordering (e.g., sorted for tree maps).
	// The returned slices are of equal length, where the i-th element of the keys
	// slice corresponds to the i-th element of the values slice.
	// Returns empty slices if the map is empty.
	//
	// Example:
	//   keys, values := m.Entries()
	//   for i := 0; i < len(keys); i++ {
	//       fmt.Printf("Key: %v, Value: %v\n", keys[i], values[i])
	//   }
	Entries() (keys []K, vals []V)

	// Clone returns a clone of the map using the same implementation,
	// duplicating all keys and values.
	Clone() Map[K, V]
}

Map is a generic interface for key-value mappings, where keys are unique and map to a single value. Implementations (e.g., hash maps, tree maps) must support all operations defined here. This interface does not assume any specific ordering of keys, making it suitable for both ordered and unordered maps.

Type parameter K must be comparable to ensure keys can be used in equality checks. Type parameter V represents the value type and has no constraints, allowing any type to be stored as a value.

The Map interface extends Container[V], inheriting operations like Len, IsEmpty, and Clear, where the element type is the value type V.

type OrderedBiMap added in v0.9.0

type OrderedBiMap[K comparable, V comparable] interface {
	OrderedMap[K, V]

	// GetKey retrieves the key associated with the specified value.
	// Returns the key and true if the value was found, or the zero value of K
	// and false if the value was not present.
	GetKey(val V) (key K, found bool)

	// HasValue returns true if the map contains the value.
	HasValue(val V) bool

	// DeleteValue removes the key-value pair associated with the specified value.
	// Returns the key and true if the value was found and removed, false if the value was not present.
	DeleteValue(val V) (key K, found bool)
}

OrderedBiMap is a generic interface for bidirectional maps that maintain a specific ordering of keys. It combines the features of an OrderedMap and a BiMap, supporting lookups by both keys and values while preserving key order.

Both keys and values must be unique and comparable. Type parameter K must be comparable for key equality and ordering, and V must be comparable for value uniqueness and lookup.

OrderedBiMap inherits all operations from OrderedMap and BiMap, providing a comprehensive set of features for ordered, bidirectional key-value mappings.

type OrderedMap added in v0.4.0

type OrderedMap[K comparable, V any] interface {
	Map[K, V]

	// Begin returns the first key-value pair in the map's ordering.
	// For ordered implementations (e.g., tree maps), this is the smallest key
	// according to the map's comparison function.
	// Returns the key, value, and true if the map is non-empty, or zero values
	// and false if the map is empty.
	Begin() (key K, val V, ok bool)

	// End returns the last key-value pair in the map's ordering.
	// For ordered implementations, this is the largest key according to the
	// map's comparison function.
	// Returns the key, value, and true if the map is non-empty, or zero values
	// and false if the map is empty.
	End() (key K, val V, ok bool)

	// DeleteBegin removes and returns the first key-value pair in the map's ordering.
	// For ordered implementations, this removes the smallest key.
	// Returns the key, value, and true if the map was non-empty, or zero values
	// and false if the map was empty.
	DeleteBegin() (key K, val V, ok bool)

	// DeleteEnd removes and returns the last key-value pair in the map's ordering.
	// For ordered implementations, this removes the largest key.
	// Returns the key, value, and true if the map was non-empty, or zero values
	// and false if the map was empty.
	DeleteEnd() (key K, val V, ok bool)

	// Iter returns an iterator over the key-value pairs in the map.
	// The iterator yields pairs in the map's ordering (e.g., sorted for tree maps).
	// Suitable for range loops.
	//
	// Example:
	//   for key, value := range m.Iter() {
	//       fmt.Printf("Key: %v, Value: %v\n", key, value)
	//   }
	//
	// The iterator is safe for concurrent reads but not for concurrent writes
	// unless the implementation explicitly supports it.
	Iter() iter.Seq2[K, V]

	// RIter returns an iterator over the key-value pairs in the map.
	// The iterator yields pairs in the map's reverse ordering.
	// Suitable for range loops.
	//
	// Example:
	//   for key, value := range m.RIter() {
	//       fmt.Printf("Key: %v, Value: %v\n", key, value)
	//   }
	//
	// The iterator is safe for concurrent reads but not for concurrent writes
	// unless the implementation explicitly supports it.
	RIter() iter.Seq2[K, V]
}

OrderedMap is a generic interface for key-value mappings that maintain a specific ordering of keys, such as sorted order in tree maps. It extends the Map interface with operations that depend on this ordering, such as accessing the first or last key-value pair, iterating in order, or retrieving keys and values in the map's defined order.

Implementations must define a consistent ordering (e.g., sorted by key for tree maps). Type parameters K and V follow the same constraints as in Map.

type PQueue added in v0.7.0

type PQueue[T comparable, V cmp.Ordered] interface {
	Container[T]

	// Enqueue adds an element to the queue.
	Enqueue(val T, priority V)

	// Dequeue removes and returns the front element of the queue.
	// Returns the element and true if the queue is non-empty,
	// or the zero value of T and false if the queue is empty.
	Dequeue() (val T, priority V, ok bool)

	// Peek returns the front element of the queue without removing it.
	// Returns the element and true if the queue is non-empty,
	// or the zero value of T and false if the queue is empty.
	Peek() (val T, priority V, ok bool)
}

PQueue is a generic interface for a priority queue. It supports adding elements to the back and removing them from the front. Implementations (e.g., array-based or linked-list priority queues) must provide all operations defined here, including those inherited from Container[T] (e.g., Len, IsEmpty, Clear). Type parameter T must be comparable to enable equality checks for elements.

type Queue added in v0.2.0

type Queue[T comparable] interface {
	Container[T]

	// Enqueue adds an element to the back of the queue.
	Enqueue(val T)

	// Dequeue removes and returns the front element of the queue.
	// Returns the element and true if the queue is non-empty,
	// or the zero value of T and false if the queue is empty.
	Dequeue() (val T, ok bool)

	// Peek returns the front element of the queue without removing it.
	// Returns the element and true if the queue is non-empty,
	// or the zero value of T and false if the queue is empty.
	Peek() (val T, ok bool)
}

Queue is a generic interface for a first-in, first-out (FIFO) data structure. It supports adding elements to the back and removing them from the front. Implementations (e.g., array-based or linked-list queues) must provide all operations defined here, including those inherited from Container[T] (e.g., Len, IsEmpty, Clear). Type parameter T must be comparable to enable equality checks for elements.

type Set added in v0.2.0

type Set[T comparable] interface {
	Container[T]

	// Clone returns a clone of the set using the same
	// implementation, duplicating all keys.
	Clone() Set[T]

	// Add adds an element to the set. Returns whether
	// the item was added.
	Add(val T) bool

	// Append multiple elements to the set. Returns
	// the number of elements added.
	Append(val ...T) int

	// Remove removes a single element from the set.
	Remove(i T)

	// RemoveAll removes multiple elements from the set.
	RemoveAll(i ...T)

	// Pop removes and returns an arbitrary item from the set.
	Pop() (val T, ok bool)

	// ContainsOne returns whether the given item
	// is in the set.
	//
	// Contains may cause the argument to escape to the heap.
	// See: https://github.com/deckarep/golang-set/issues/118
	ContainsOne(val T) bool

	// Contains returns whether the given items
	// are all in the set.
	Contains(val ...T) bool

	// ContainsAny returns whether at least one of the
	// given items are in the set.
	ContainsAny(val ...T) bool

	// ContainsAnyElement returns whether at least one of the
	// given element are in the set.
	ContainsAnyElement(other Set[T]) bool

	// Equal determines if two sets are equal to each
	// other. If they have the same cardinality
	// and contain the same elements, they are
	// considered equal. The order in which
	// the elements were added is irrelevant.
	//
	// Note that the argument to Equal must be
	// of the same type as the receiver of the
	// method. Otherwise, Equal will panic.
	Equal(other Set[T]) bool

	// IsSubset determines if every element in this set is in
	// the other set.
	//
	// Note that the argument to IsSubset
	// must be of the same type as the receiver
	// of the method. Otherwise, IsSubset will panic.
	IsSubset(other Set[T]) bool

	// IsProperSubset determines if every element in this set is in
	// the other set but the two sets are not equal.
	//
	// Note that the argument to IsProperSubset
	// must be of the same type as the receiver
	// of the method. Otherwise, IsProperSubset will panic.
	IsProperSubset(other Set[T]) bool

	// IsSuperset determines if every element in the other set
	// is in this set.
	//
	// Note that the argument to IsSuperset
	// must be of the same type as the receiver
	// of the method. Otherwise, IsSuperset will panic.
	IsSuperset(other Set[T]) bool

	// IsProperSuperset determines if every element in the other set
	// is in this set but the two sets are not
	// equal.
	//
	// Note that the argument to IsSuperset
	// must be of the same type as the receiver
	// of the method. Otherwise, IsSuperset will
	// panic.
	IsProperSuperset(other Set[T]) bool

	// Union returns a new set with all elements in both sets.
	//
	// Note that the argument to Union must be of the
	// same type as the receiver of the method.
	// Otherwise, Union will panic.
	Union(other Set[T]) Set[T]

	// Intersect returns a new set containing only the elements
	// that exist only in both sets.
	//
	// Note that the argument to Intersect
	// must be of the same type as the receiver
	// of the method. Otherwise, Intersect will
	// panic.
	Intersect(other Set[T]) Set[T]

	// Difference returns the difference between this set
	// and other. The returned set will contain
	// all elements of this set that are not also
	// elements of other.
	//
	// Note that the argument to Difference
	// must be of the same type as the receiver
	// of the method. Otherwise, Difference will
	// panic.
	Difference(other Set[T]) Set[T]

	// SymmetricDifference returns a new set with all elements which are
	// in either this set or the other set but not in both.
	//
	// Note that the argument to SymmetricDifference
	// must be of the same type as the receiver
	// of the method. Otherwise, SymmetricDifference will
	// panic.
	SymmetricDifference(other Set[T]) Set[T]

	// Iter returns a channel of elements that you can
	// range over.
	Iter() iter.Seq[T]
}

Set is the primary interface provided by the mapset package. It represents an unordered set of data and a large number of operations that can be applied to that set.

type Stack added in v0.7.0

type Stack[T comparable] interface {
	Container[T]

	// Push adds an element to the top of the stack.
	Push(val T)

	// Pop removes and returns the top element of the stack.
	// Returns the element and true if the stack is non-empty,
	// or the zero value of T and false if the stack is empty.
	Pop() (val T, ok bool)

	// Peek returns the top element of the stack without removing it.
	// Returns the element and true if the stack is non-empty,
	// or the zero value of T and false if the stack is empty.
	Peek() (val T, ok bool)
}

Stack is a generic interface for a last-in, first-out (LIFO) data structure. It supports adding elements to the top (push) and removing them from the top (pop). Implementations (e.g., array-based or linked-list stacks) must provide all operations defined here, including those inherited from Container[T] (e.g., Len, IsEmpty, Clear). Type parameter T must be comparable to enable equality checks for elements, if needed by specific implementations, though stack operations themselves (Push, Pop, Peek) do not inherently require comparability.

Jump to

Keyboard shortcuts

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