Documentation
¶
Overview ¶
Package g provides an ergonomic standard library extension for Go: monadic error handling, rich generic containers, lazy iterators with type-changing generic methods (Go 1.27+), and ergonomic wrappers for primitive types and the filesystem.
Monads ¶
Option represents an optional value (Some/None) and Result represents success or failure (Ok/Err). Both offer chainable combinators — Map, Then, UnwrapOr, MapOr, Inspect and friends — so error and nil handling become expressions instead of if-ladders.
Containers ¶
- Slice: an extended slice with 90+ methods.
- Map: a map with ergonomic accessors and entry API.
- MapOrd: an insertion-ordered map.
- MapSafe: a concurrency-safe map.
- Set: a hash set with algebraic operations (union, intersection, ...).
- Deque: a double-ended queue backed by a ring buffer.
- Heap: a binary min/max heap driven by a comparison function.
Iterators ¶
Every container exposes Iter/IntoIter methods returning lazy sequences — SeqSlice, SeqSlices, SeqSet, SeqMap, SeqMapOrd, SeqDeque, SeqHeap, SeqResult and SeqPairs — built on top of github.com/enetx/iter. With Go 1.27 generic methods, transformations can change the element type mid-chain:
g.SliceOf(1, 2, 3).Iter().Map[string](strconv.Itoa).Collect() // Slice[string]
Iterators are lazy: nothing is computed until a consumer (Collect, ForEach, Fold, ...) runs the chain.
Primitive wrappers ¶
String, Int, Float and Bytes wrap the built-in types with fluent methods, including conversion pipelines via Encode/Decode (Base64, Hex, Octal, Binary, JSON, ...), Compress/Decompress (gzip, zstd, brotli, ...) and Hash (MD5, SHA1, SHA256, SHA512).
Filesystem ¶
File and Dir provide chainable, Result-based file and directory operations, including lazy line/chunk iterators over file contents.
Subpackages ¶
- pool: a generic goroutine pool with limits, rate limiting and streaming.
- cmp: ordering primitives (cmp.Ordering, cmp.Cmp) used by sorts and heaps.
- f: predicate combinators for filters (f.Eq, f.Gt, f.Contains, ...).
- ref: pointer helpers (ref.Of).
- constraints: generic type constraints shared across the library.
- dbg: debugging helpers that print expressions with source locations.
Panics ¶
The library reports failures through Result and Option; panics are reserved for programmer errors. Only two families of API panic:
- the Unwrap/Expect family on Option and Result (Unwrap, UnwrapErr, Expect) when called on the wrong variant;
- documented index-based operations (e.g. Slice.Swap/Insert/Replace/SubSlice, Deque.Insert/Swap) when given out-of-range indices, and constructors with documented preconditions (e.g. NewHeap with a nil comparison function).
Everything else returns Option/Result instead of panicking.
Security ¶
Format templates can invoke arbitrary exported methods on their arguments via reflection ({key.Method(...)} placeholders). Treat templates as code: never pass untrusted or user-controlled input as the template string — untrusted data belongs only in argument values.
Index ¶
- Constants
- Variables
- func Errorf[T ~string](format T, args ...any) error
- func FormatTo[T ~string](builder *Builder, template T, args ...any)
- type Builder
- func (b *Builder) Cap() Int
- func (b *Builder) Grow(n Int)
- func (b *Builder) Len() Int
- func (b *Builder) Reset()
- func (b *Builder) String() String
- func (b *Builder) Write(bs []byte) (int, error)
- func (b *Builder) WriteByte(c byte) error
- func (b *Builder) WriteRune(r rune) (int, error)
- func (b *Builder) WriteString(str String) (int, error)
- type Bytes
- func (bs Bytes) Append(obs Bytes) Bytes
- func (bs Bytes) Center(length Int, pad Bytes) Bytes
- func (bs Bytes) Chars() SeqSlice[Bytes]
- func (bs Bytes) Chunks(size Int) SeqSlice[Bytes]
- func (bs Bytes) Clone() Bytes
- func (bs Bytes) Cmp(obs Bytes) cmp.Ordering
- func (bs Bytes) Compress() bcompress
- func (bs Bytes) Contains(obs Bytes) bool
- func (bs Bytes) ContainsAll(obss ...Bytes) bool
- func (bs Bytes) ContainsAny(obss ...Bytes) bool
- func (bs Bytes) ContainsAnyChars(chars String) bool
- func (bs Bytes) ContainsRune(r rune) bool
- func (bs Bytes) Count(obs Bytes) Int
- func (bs Bytes) Cut(start, end Bytes, rmtags ...bool) (Bytes, Bytes)
- func (bs Bytes) Decode() bdecode
- func (bs Bytes) Decompress() bdecompress
- func (bs Bytes) Encode() bencode
- func (bs Bytes) EndsWith(suffix Bytes) bool
- func (bs Bytes) EndsWithAny(suffixes ...Bytes) bool
- func (bs Bytes) Eq(obs Bytes) bool
- func (bs Bytes) EqFold(obs Bytes) bool
- func (bs Bytes) Fields() SeqSlice[Bytes]
- func (bs Bytes) FieldsBy(fn func(r rune) bool) SeqSlice[Bytes]
- func (bs Bytes) FloatBE() Float
- func (bs Bytes) FloatLE() Float
- func (bs Bytes) Gt(obs Bytes) bool
- func (bs Bytes) Gte(obs Bytes) bool
- func (bs Bytes) Hash() bhash
- func (bs Bytes) Index(obs Bytes) Int
- func (bs Bytes) IndexByte(b byte) Int
- func (bs Bytes) IndexRune(r rune) Int
- func (bs Bytes) IntBE() Int
- func (bs Bytes) IntLE() Int
- func (bs Bytes) IsASCII() bool
- func (bs Bytes) IsDigit() bool
- func (bs Bytes) IsEmpty() bool
- func (bs Bytes) IsLower() bool
- func (bs Bytes) IsTitle() bool
- func (bs Bytes) IsUpper() bool
- func (bs Bytes) LastIndex(obs Bytes) Int
- func (bs Bytes) LastIndexByte(b byte) Int
- func (bs Bytes) LeftJustify(length Int, pad Bytes) Bytes
- func (bs Bytes) Len() Int
- func (bs Bytes) LenRunes() Int
- func (bs Bytes) Lines() SeqSlice[Bytes]
- func (bs Bytes) Lower() Bytes
- func (bs Bytes) Lt(obs Bytes) bool
- func (bs Bytes) Lte(obs Bytes) bool
- func (bs Bytes) Map(fn func(rune) rune) Bytes
- func (bs Bytes) Max(b ...Bytes) Bytes
- func (bs Bytes) Min(b ...Bytes) Bytes
- func (bs Bytes) Ne(obs Bytes) bool
- func (bs Bytes) NormalizeNFC() Bytes
- func (bs Bytes) Prepend(obs Bytes) Bytes
- func (bs Bytes) Print() Bytes
- func (bs Bytes) Println() Bytes
- func (bs Bytes) Reader() *bytes.Reader
- func (bs Bytes) Regexp() regexpb
- func (bs Bytes) Remove(patterns ...Bytes) Bytes
- func (bs Bytes) Repeat(count Int) Bytes
- func (bs Bytes) Replace(oldB, newB Bytes, n Int) Bytes
- func (bs Bytes) ReplaceAll(oldB, newB Bytes) Bytes
- func (bs Bytes) ReplaceMulti(oldnew ...Bytes) Bytes
- func (bs Bytes) ReplaceNth(oldB, newB Bytes, n Int) Bytes
- func (bs *Bytes) Reset()
- func (bs Bytes) Reverse() Bytes
- func (bs Bytes) RightJustify(length Int, pad Bytes) Bytes
- func (bs Bytes) Runes() Slice[rune]
- func (bs *Bytes) Scan(src any) error
- func (bs Bytes) Similarity(obs Bytes) Float
- func (bs Bytes) Split(sep Bytes) SeqSlice[Bytes]
- func (bs Bytes) SplitAfter(sep Bytes) SeqSlice[Bytes]
- func (bs Bytes) SplitN(sep Bytes, n Int) Slice[Bytes]
- func (bs Bytes) StartsWith(prefix Bytes) bool
- func (bs Bytes) StartsWithAny(prefixes ...Bytes) bool
- func (bs Bytes) Std() []byte
- func (bs Bytes) String() String
- func (bs Bytes) StringUnsafe() String
- func (bs Bytes) StripPrefix(cutset Bytes) Bytes
- func (bs Bytes) StripSuffix(cutset Bytes) Bytes
- func (bs Bytes) SubBytes(start, end Int, step ...Int) Bytes
- func (bs Bytes) Title() Bytes
- func (bs Bytes) Transform[U any](fn func(Bytes) U) U
- func (bs Bytes) Trim() Bytes
- func (bs Bytes) TrimEnd() Bytes
- func (bs Bytes) TrimEndSet(cutset String) Bytes
- func (bs Bytes) TrimSet(cutset String) Bytes
- func (bs Bytes) TrimStart() Bytes
- func (bs Bytes) TrimStartSet(cutset String) Bytes
- func (bs Bytes) Truncate(max Int) Bytes
- func (bs Bytes) TryBigInt() Result[*big.Int]
- func (bs Bytes) TryBool() Result[bool]
- func (bs Bytes) TryComplex() Result[complex128]
- func (bs Bytes) TryFloat() Result[Float]
- func (bs Bytes) TryInt() Result[Int]
- func (bs Bytes) TryUint() Result[uint]
- func (bs Bytes) Upper() Bytes
- func (bs Bytes) Value() (driver.Value, error)
- type Deque
- func (dq *Deque[T]) Back() Option[T]
- func (dq *Deque[T]) BinarySearch(value T, fn func(T, T) cmp.Ordering) (Int, bool)
- func (dq *Deque[T]) Capacity() Int
- func (dq *Deque[T]) Clear()
- func (dq *Deque[T]) Clone() *Deque[T]
- func (dq *Deque[T]) Contains(value T) bool
- func (dq *Deque[T]) ContainsAll(values ...T) bool
- func (dq *Deque[T]) ContainsAny(values ...T) bool
- func (dq *Deque[T]) Eq(other *Deque[T]) bool
- func (dq *Deque[T]) Extend(values ...T)
- func (dq *Deque[T]) Front() Option[T]
- func (dq *Deque[T]) Get(index Int) Option[T]
- func (dq *Deque[T]) Index(value T) Int
- func (dq *Deque[T]) Insert(index Int, value T)
- func (dq *Deque[T]) IsEmpty() bool
- func (dq *Deque[T]) Iter() SeqDeque[T]
- func (dq *Deque[T]) IterReverse() SeqDeque[T]
- func (dq *Deque[T]) Len() Int
- func (dq *Deque[T]) MakeContiguous() Slice[T]
- func (dq *Deque[T]) Ne(other *Deque[T]) bool
- func (dq *Deque[T]) PopBack() Option[T]
- func (dq *Deque[T]) PopFront() Option[T]
- func (dq *Deque[T]) Print() *Deque[T]
- func (dq *Deque[T]) Println() *Deque[T]
- func (dq *Deque[T]) PushBack(value T)
- func (dq *Deque[T]) PushFront(value T)
- func (dq *Deque[T]) Remove(index Int) Option[T]
- func (dq *Deque[T]) Reserve(additional Int)
- func (dq *Deque[T]) Retain(predicate func(T) bool)
- func (dq *Deque[T]) RotateLeft(mid Int)
- func (dq *Deque[T]) RotateRight(k Int)
- func (dq *Deque[T]) Set(index Int, value T) Option[T]
- func (dq *Deque[T]) ShrinkToFit()
- func (dq *Deque[T]) Slice() Slice[T]
- func (dq *Deque[T]) String() string
- func (dq *Deque[T]) Swap(i, j Int)
- func (dq *Deque[T]) Transform[U any](fn func(*Deque[T]) U) U
- type Dir
- func (d *Dir) Chown(uid, gid int) Result[*Dir]
- func (d *Dir) Copy(dest String, followLinks ...bool) Result[*Dir]
- func (d *Dir) Create(mode ...os.FileMode) Result[*Dir]
- func (d *Dir) CreateAll(mode ...os.FileMode) Result[*Dir]
- func (d *Dir) Exists() bool
- func (d *Dir) Glob() SeqResult[*File]
- func (d *Dir) IsLink() bool
- func (d *Dir) Join(elem ...String) Result[String]
- func (d *Dir) Lstat() Result[fs.FileInfo]
- func (d *Dir) Move(newpath String) Result[*Dir]
- func (d *Dir) Path() Result[String]
- func (d *Dir) Print() *Dir
- func (d *Dir) Println() *Dir
- func (d *Dir) Read() SeqResult[*File]
- func (d *Dir) Remove() Result[*Dir]
- func (d *Dir) Rename(newpath String) Result[*Dir]
- func (d *Dir) SetPath(path String) *Dir
- func (d *Dir) Stat() Result[fs.FileInfo]
- func (d *Dir) String() String
- func (d *Dir) Walk() SeqResult[*File]
- type Entry
- type ErrFileClosed
- type ErrFileNotExist
- type File
- func (f *File) Append(content String, mode ...os.FileMode) Result[*File]
- func (f *File) Chmod(mode os.FileMode) Result[*File]
- func (f *File) Chown(uid, gid int) Result[*File]
- func (f *File) Chunks(size Int) SeqResult[String]
- func (f *File) ChunksRaw(size Int) SeqResult[Bytes]
- func (f *File) Close() error
- func (f *File) Copy(dest String, mode ...os.FileMode) Result[*File]
- func (f *File) Create() Result[*File]
- func (f *File) CreateTemp(args ...String) Result[*File]
- func (f *File) Decode() fdecode
- func (f *File) Dir() Result[*Dir]
- func (f *File) Encode() fencode
- func (f *File) Exists() bool
- func (f *File) Ext() String
- func (f *File) Guard() *File
- func (f *File) IsDir() bool
- func (f *File) IsLink() bool
- func (f *File) Lines() SeqResult[String]
- func (f *File) LinesRaw() SeqResult[Bytes]
- func (f *File) Lstat() Result[fs.FileInfo]
- func (f *File) MimeType() Result[String]
- func (f *File) Move(newpath String) Result[*File]
- func (f *File) Name() String
- func (f *File) Open() Result[*File]
- func (f *File) OpenFile(flag int, perm fs.FileMode) Result[*File]
- func (f *File) Path() Result[String]
- func (f *File) Print() *File
- func (f *File) Println() *File
- func (f *File) Read() Result[String]
- func (f *File) Reader() Result[io.ReadCloser]
- func (f *File) Remove() Result[*File]
- func (f *File) Rename(newpath String) Result[*File]
- func (f *File) Seek(offset int64, whence int) Result[*File]
- func (f *File) Split() (*Dir, *File)
- func (f *File) Stat() Result[fs.FileInfo]
- func (f *File) Std() *os.File
- func (f *File) Write(content String, mode ...os.FileMode) Result[*File]
- func (f *File) WriteFromReader(scr io.Reader, mode ...os.FileMode) Result[*File]
- type Float
- func (f Float) Abs() Float
- func (f Float) Acos() Float
- func (f Float) Acosh() Float
- func (f Float) Add(b Float) Float
- func (f Float) Asin() Float
- func (f Float) Asinh() Float
- func (f Float) Atan() Float
- func (f Float) Atan2(b Float) Float
- func (f Float) Atanh() Float
- func (f Float) BigFloat() *big.Float
- func (f Float) Bits() uint64
- func (f Float) BytesBE() Bytes
- func (f Float) BytesLE() Bytes
- func (f Float) Cbrt() Float
- func (f Float) Ceil() Float
- func (f Float) CeilDecimal(precision Int) Float
- func (f Float) Clamp(min, max Float) Float
- func (f Float) Cmp(b Float) cmp.Ordering
- func (f Float) Copysign(sign Float) Float
- func (f Float) Cos() Float
- func (f Float) Cosh() Float
- func (f Float) Div(b Float) Float
- func (f Float) Eq(b Float) bool
- func (f Float) Exp() Float
- func (f Float) Exp2() Float
- func (f Float) ExpM1() Float
- func (f Float) Float32() float32
- func (f Float) Floor() Float
- func (f Float) FloorDecimal(precision Int) Float
- func (f Float) Fract() Float
- func (f Float) Gt(b Float) bool
- func (f Float) Gte(b Float) bool
- func (f Float) Hypot(b Float) Float
- func (f Float) Int() Int
- func (f Float) IsFinite() bool
- func (f Float) IsInf() bool
- func (f Float) IsNaN() bool
- func (f Float) IsNormal() bool
- func (f Float) IsSignNegative() bool
- func (f Float) IsSignPositive() bool
- func (f Float) IsZero() bool
- func (f Float) Ln() Float
- func (f Float) Ln1p() Float
- func (f Float) Log2() Float
- func (f Float) Log10() Float
- func (f Float) Lt(b Float) bool
- func (f Float) Lte(b Float) bool
- func (f Float) Max(b ...Float) Float
- func (f Float) Min(b ...Float) Float
- func (f Float) Mod(b Float) Float
- func (f Float) Mul(b Float) Float
- func (f Float) MulAdd(b, c Float) Float
- func (f Float) Ne(b Float) bool
- func (f Float) Neg() Float
- func (f Float) Pow(exp Float) Float
- func (f Float) Print() Float
- func (f Float) Println() Float
- func (f Float) Recip() Float
- func (f Float) Round() Int
- func (f Float) RoundDecimal(precision Int) Float
- func (f *Float) Scan(src any) error
- func (f Float) Signum() Float
- func (f Float) Sin() Float
- func (f Float) Sinh() Float
- func (f Float) Sqrt() Float
- func (f Float) Std() float64
- func (f Float) String() String
- func (f Float) Sub(b Float) Float
- func (f Float) Tan() Float
- func (f Float) Tanh() Float
- func (f Float) ToDegrees() Float
- func (f Float) ToRadians() Float
- func (f Float) Transform[U any](fn func(Float) U) U
- func (f Float) Trunc() Float
- func (f Float) TruncDecimal(precision Int) Float
- func (f Float) Value() (driver.Value, error)
- type Formattable
- type Heap
- func (h *Heap[T]) Clear()
- func (h *Heap[T]) Clone() *Heap[T]
- func (h *Heap[T]) Contains(value T) bool
- func (h *Heap[T]) Eq(other *Heap[T]) bool
- func (h *Heap[T]) Fix(i Int)
- func (h *Heap[T]) IntoIter() SeqHeap[T]
- func (h *Heap[T]) IsEmpty() bool
- func (h *Heap[T]) Iter() SeqHeap[T]
- func (h *Heap[T]) Len() Int
- func (h *Heap[T]) Ne(other *Heap[T]) bool
- func (h *Heap[T]) Peek() Option[T]
- func (h *Heap[T]) Pop() Option[T]
- func (h *Heap[T]) Print() *Heap[T]
- func (h *Heap[T]) Println() *Heap[T]
- func (h *Heap[T]) Push(items ...T)
- func (h *Heap[T]) Remove(i Int) Option[T]
- func (h *Heap[T]) Slice() Slice[T]
- func (h *Heap[T]) String() string
- func (h *Heap[T]) Transform[U any](fn func(*Heap[T]) U) U
- type Int
- func (i Int) Abs() Int
- func (i Int) Add(b Int) Int
- func (i Int) BigInt() *big.Int
- func (i Int) Binary() String
- func (i Int) BytesBE() Bytes
- func (i Int) BytesLE() Bytes
- func (i Int) CheckedAbs() Option[Int]
- func (i Int) CheckedAdd(b Int) Option[Int]
- func (i Int) CheckedDiv(b Int) Option[Int]
- func (i Int) CheckedMul(b Int) Option[Int]
- func (i Int) CheckedNeg() Option[Int]
- func (i Int) CheckedPow(exp Int) Option[Int]
- func (i Int) CheckedRem(b Int) Option[Int]
- func (i Int) CheckedSub(b Int) Option[Int]
- func (i Int) Clamp(min, max Int) Int
- func (i Int) Cmp(b Int) cmp.Ordering
- func (i Int) Div(b Int) Int
- func (i Int) Eq(b Int) bool
- func (i Int) Float() Float
- func (i Int) Gt(b Int) bool
- func (i Int) Gte(b Int) bool
- func (i Int) Hex() String
- func (i Int) Int8() int8
- func (i Int) Int16() int16
- func (i Int) Int32() int32
- func (i Int) Int64() int64
- func (i Int) IsNegative() bool
- func (i Int) IsPositive() bool
- func (i Int) IsZero() bool
- func (i Int) Lt(b Int) bool
- func (i Int) Lte(b Int) bool
- func (i Int) Max(b ...Int) Int
- func (i Int) Min(b ...Int) Int
- func (i Int) Mul(b Int) Int
- func (i Int) Ne(b Int) bool
- func (i Int) Neg() Int
- func (i Int) Octal() String
- func (i Int) OverflowingAdd(b Int) (Int, bool)
- func (i Int) OverflowingMul(b Int) (Int, bool)
- func (i Int) OverflowingSub(b Int) (Int, bool)
- func (i Int) Print() Int
- func (i Int) Println() Int
- func (i Int) Random() Int
- func (i Int) RandomRange(to Int) Int
- func (i Int) Rem(b Int) Int
- func (i Int) SaturatingAdd(b Int) Int
- func (i Int) SaturatingMul(b Int) Int
- func (i Int) SaturatingSub(b Int) Int
- func (i *Int) Scan(src any) error
- func (i Int) Signum() Int
- func (i Int) Std() int
- func (i Int) String() String
- func (i Int) Sub(b Int) Int
- func (i Int) Transform[U any](fn func(Int) U) U
- func (i Int) UInt() uint
- func (i Int) UInt8() uint8
- func (i Int) UInt16() uint16
- func (i Int) UInt32() uint32
- func (i Int) UInt64() uint64
- func (i Int) Value() (driver.Value, error)
- type Map
- func (m Map[K, V]) Clear()
- func (m Map[K, V]) Clone() Map[K, V]
- func (m Map[K, V]) Contains(key K) bool
- func (m Map[K, V]) Copy(src Map[K, V])
- func (m Map[K, V]) Entry(key K) Entry[K, V]
- func (m Map[K, V]) Eq(other Map[K, V]) bool
- func (m Map[K, V]) Get(k K) Option[V]
- func (m Map[K, V]) Insert(key K, value V) Option[V]
- func (m Map[K, V]) IsEmpty() bool
- func (m Map[K, V]) Iter() SeqMap[K, V]
- func (m Map[K, V]) Keys() Slice[K]
- func (m Map[K, V]) Len() Int
- func (m Map[K, V]) Ne(other Map[K, V]) bool
- func (m Map[K, V]) Ordered() MapOrd[K, V]
- func (m Map[K, V]) Print() Map[K, V]
- func (m Map[K, V]) Println() Map[K, V]
- func (m Map[K, V]) Remove(key K) Option[V]
- func (m Map[K, V]) Safe() *MapSafe[K, V]
- func (m Map[K, V]) Std() map[K]V
- func (m Map[K, V]) String() string
- func (m Map[K, V]) Transform[U any](fn func(Map[K, V]) U) U
- func (m Map[K, V]) Values() Slice[V]
- type MapOrd
- func (mo *MapOrd[K, V]) Clear()
- func (mo MapOrd[K, V]) Clone() MapOrd[K, V]
- func (mo MapOrd[K, V]) Contains(key K) bool
- func (mo *MapOrd[K, V]) Copy(src MapOrd[K, V])
- func (mo *MapOrd[K, V]) Entry(key K) OrdEntry[K, V]
- func (mo MapOrd[K, V]) Eq(other MapOrd[K, V]) bool
- func (mo MapOrd[K, V]) Get(key K) Option[V]
- func (mo *MapOrd[K, V]) Insert(key K, value V) Option[V]
- func (mo MapOrd[K, V]) IsEmpty() bool
- func (mo MapOrd[K, V]) IsSortedBy(fn func(a, b Pair[K, V]) cmp.Ordering) bool
- func (mo MapOrd[K, V]) IsSortedByKey(fn func(a, b K) cmp.Ordering) bool
- func (mo MapOrd[K, V]) IsSortedByValue(fn func(a, b V) cmp.Ordering) bool
- func (mo MapOrd[K, V]) Iter() SeqMapOrd[K, V]
- func (mo MapOrd[K, V]) IterReverse() SeqMapOrd[K, V]
- func (mo MapOrd[K, V]) Keys() Slice[K]
- func (mo MapOrd[K, V]) Len() Int
- func (mo MapOrd[K, V]) Map() Map[K, V]
- func (mo MapOrd[K, V]) Ne(other MapOrd[K, V]) bool
- func (mo MapOrd[K, V]) Print() MapOrd[K, V]
- func (mo MapOrd[K, V]) Println() MapOrd[K, V]
- func (mo *MapOrd[K, V]) Remove(key K) Option[V]
- func (mo MapOrd[K, V]) Safe() *MapSafe[K, V]
- func (mo MapOrd[K, V]) Shuffle()
- func (mo MapOrd[K, V]) SortBy(fn func(a, b Pair[K, V]) cmp.Ordering)
- func (mo MapOrd[K, V]) SortByKey(fn func(a, b K) cmp.Ordering)
- func (mo MapOrd[K, V]) SortByValue(fn func(a, b V) cmp.Ordering)
- func (mo MapOrd[K, V]) String() string
- func (mo MapOrd[K, V]) Transform[U any](fn func(MapOrd[K, V]) U) U
- func (mo MapOrd[K, V]) Values() Slice[V]
- type MapSafe
- func (ms *MapSafe[K, V]) Clear()
- func (ms *MapSafe[K, V]) Clone() *MapSafe[K, V]
- func (ms *MapSafe[K, V]) Contains(key K) bool
- func (ms *MapSafe[K, V]) Copy(src *MapSafe[K, V])
- func (ms *MapSafe[K, V]) Entry(key K) SafeEntry[K, V]
- func (ms *MapSafe[K, V]) Eq(other *MapSafe[K, V]) bool
- func (ms *MapSafe[K, V]) Get(key K) Option[V]
- func (ms *MapSafe[K, V]) Insert(key K, value V) Option[V]
- func (ms *MapSafe[K, V]) IsEmpty() bool
- func (ms *MapSafe[K, V]) Iter() SeqMap[K, V]
- func (ms *MapSafe[K, V]) Keys() Slice[K]
- func (ms *MapSafe[K, V]) Len() Int
- func (ms *MapSafe[K, V]) Map() Map[K, V]
- func (ms *MapSafe[K, V]) Ne(other *MapSafe[K, V]) bool
- func (ms *MapSafe[K, V]) Ordered() MapOrd[K, V]
- func (ms *MapSafe[K, V]) Print() *MapSafe[K, V]
- func (ms *MapSafe[K, V]) Println() *MapSafe[K, V]
- func (ms *MapSafe[K, V]) Remove(key K) Option[V]
- func (ms *MapSafe[K, V]) String() string
- func (ms *MapSafe[K, V]) Transform[U any](fn func(*MapSafe[K, V]) U) U
- func (ms *MapSafe[K, V]) TryInsert(key K, value V) Option[V]
- func (ms *MapSafe[K, V]) Values() Slice[V]
- type Mutex
- type MutexGuard
- type Named
- type OccupiedEntry
- func (e OccupiedEntry[K, V]) AndModify(fn func(*V)) Entry[K, V]
- func (e OccupiedEntry[K, V]) Get() V
- func (e OccupiedEntry[K, V]) Insert(value V) V
- func (e OccupiedEntry[K, V]) Key() K
- func (e OccupiedEntry[K, V]) OrDefault() V
- func (e OccupiedEntry[K, V]) OrInsert(value V) V
- func (e OccupiedEntry[K, V]) OrInsertWith(fn func() V) V
- func (e OccupiedEntry[K, V]) OrInsertWithKey(fn func(K) V) V
- func (e OccupiedEntry[K, V]) Remove() V
- type OccupiedOrdEntry
- func (e OccupiedOrdEntry[K, V]) AndModify(fn func(*V)) OrdEntry[K, V]
- func (e OccupiedOrdEntry[K, V]) Get() V
- func (e OccupiedOrdEntry[K, V]) Insert(value V) V
- func (e OccupiedOrdEntry[K, V]) Key() K
- func (e OccupiedOrdEntry[K, V]) OrDefault() V
- func (e OccupiedOrdEntry[K, V]) OrInsert(value V) V
- func (e OccupiedOrdEntry[K, V]) OrInsertWith(fn func() V) V
- func (e OccupiedOrdEntry[K, V]) OrInsertWithKey(fn func(K) V) V
- func (e OccupiedOrdEntry[K, V]) Remove() V
- type OccupiedSafeEntry
- func (e OccupiedSafeEntry[K, V]) AndModify(fn func(*V)) SafeEntry[K, V]
- func (e OccupiedSafeEntry[K, V]) Get() V
- func (e OccupiedSafeEntry[K, V]) Insert(value V) V
- func (e OccupiedSafeEntry[K, V]) Key() K
- func (e OccupiedSafeEntry[K, V]) OrDefault() V
- func (e OccupiedSafeEntry[K, V]) OrInsert(value V) V
- func (e OccupiedSafeEntry[K, V]) OrInsertWith(fn func() V) V
- func (e OccupiedSafeEntry[K, V]) OrInsertWithKey(fn func(K) V) V
- func (e OccupiedSafeEntry[K, V]) Remove() V
- type Option
- func (o Option[T]) And[U any](other Option[U]) Option[U]
- func (o Option[T]) Expect(msg string) T
- func (o Option[T]) Filter(pred func(T) bool) Option[T]
- func (o *Option[T]) GetOrInsert(value T) *T
- func (o *Option[T]) GetOrInsertWith(fn func() T) *T
- func (o *Option[T]) Insert(value T) *T
- func (o Option[T]) Inspect(fn func(T)) Option[T]
- func (o Option[T]) IsNone() bool
- func (o Option[T]) IsNoneOr(pred func(T) bool) bool
- func (o Option[T]) IsSome() bool
- func (o Option[T]) IsSomeAnd(pred func(T) bool) bool
- func (o Option[T]) Map[U any](fn func(T) U) Option[U]
- func (o Option[T]) MapOr[U any](def U, fn func(T) U) U
- func (o Option[T]) MapOrElse[U any](defFn func() U, fn func(T) U) U
- func (o Option[T]) MarshalJSON() ([]byte, error)
- func (o Option[T]) MarshalJSONTo(enc *jsontext.Encoder) error
- func (o Option[T]) OkOr(err error) Result[T]
- func (o Option[T]) OkOrElse(fn func() error) Result[T]
- func (o Option[T]) Option() (T, bool)
- func (o Option[T]) Or(other Option[T]) Option[T]
- func (o Option[T]) OrElse(fn func() Option[T]) Option[T]
- func (o Option[T]) Ptr() *T
- func (o *Option[T]) Replace(value T) Option[T]
- func (o *Option[T]) Scan(src any) error
- func (o Option[T]) Some() T
- func (o Option[T]) String() string
- func (o *Option[T]) Take() Option[T]
- func (o Option[T]) Then[U any](fn func(T) Option[U]) Option[U]
- func (o Option[T]) ThenOf[U any](fn func(T) (U, bool)) Option[U]
- func (o *Option[T]) UnmarshalJSON(data []byte) error
- func (o *Option[T]) UnmarshalJSONFrom(dec *jsontext.Decoder) error
- func (o Option[T]) Unwrap() T
- func (o Option[T]) UnwrapOr(value T) T
- func (o Option[T]) UnwrapOrDefault() T
- func (o Option[T]) Value() (driver.Value, error)
- func (o Option[T]) Xor(other Option[T]) Option[T]
- type OrdEntry
- type Pair
- type Result
- func CreateTempDir(args ...String) Result[*Dir]
- func Eprint[T ~string](format T, args ...any) Result[int]
- func Eprintln[T ~string](format T, args ...any) Result[int]
- func Err[T any](err error) Result[T]
- func Ok[T any](value T) Result[T]
- func Print[T ~string](format T, args ...any) Result[int]
- func Println[T ~string](format T, args ...any) Result[int]
- func ResultOf[T any](value T, err error) Result[T]
- func TryFormat[T ~string](template T, args ...any) (result Result[String])
- func TryFormatTo[T ~string](builder *Builder, template T, args ...any) Result[Unit]
- func Write[T ~string](w io.Writer, format T, args ...any) Result[int]
- func Writeln[T ~string](w io.Writer, format T, args ...any) Result[int]
- func (r Result[T]) And[U any](other Result[U]) Result[U]
- func (r Result[T]) Err() error
- func (r Result[T]) ErrAs(target any) bool
- func (r Result[T]) ErrIs(target error) bool
- func (r Result[T]) ErrOption() Option[error]
- func (r Result[T]) ErrSource() Option[error]
- func (r Result[T]) Expect(msg string) T
- func (r Result[T]) Inspect(fn func(T)) Result[T]
- func (r Result[T]) InspectErr(fn func(error)) Result[T]
- func (r Result[T]) IsErr() bool
- func (r Result[T]) IsErrAnd(pred func(error) bool) bool
- func (r Result[T]) IsOk() bool
- func (r Result[T]) IsOkAnd(pred func(T) bool) bool
- func (r Result[T]) Map[U any](fn func(T) U) Result[U]
- func (r Result[T]) MapErr(fn func(error) error) Result[T]
- func (r Result[T]) MapOr[U any](def U, fn func(T) U) U
- func (r Result[T]) MapOrElse[U any](defFn func(error) U, fn func(T) U) U
- func (r Result[T]) MarshalJSON() ([]byte, error)
- func (r Result[T]) MarshalJSONTo(enc *jsontext.Encoder) error
- func (r Result[T]) Ok() T
- func (r Result[T]) Option() Option[T]
- func (r Result[T]) Or(other Result[T]) Result[T]
- func (r Result[T]) OrElse(fn func(error) Result[T]) Result[T]
- func (r Result[T]) Result() (T, error)
- func (r Result[T]) String() string
- func (r Result[T]) Then[U any](fn func(T) Result[U]) Result[U]
- func (r Result[T]) ThenOf[U any](fn func(T) (U, error)) Result[U]
- func (r *Result[T]) UnmarshalJSON(data []byte) error
- func (r *Result[T]) UnmarshalJSONFrom(dec *jsontext.Decoder) error
- func (r Result[T]) Unwrap() T
- func (r Result[T]) UnwrapErr() error
- func (r Result[T]) UnwrapOr(value T) T
- func (r Result[T]) UnwrapOrDefault() T
- func (r Result[T]) Wrap(err error) Result[T]
- type RwLock
- type RwLockReadGuard
- type RwLockWriteGuard
- type SafeEntry
- type SeqDeque
- func (seq SeqDeque[V]) All(fn func(v V) bool) bool
- func (seq SeqDeque[V]) Any(fn func(V) bool) bool
- func (seq SeqDeque[V]) Chain(seqs ...SeqDeque[V]) SeqDeque[V]
- func (seq SeqDeque[V]) Chan(ctxs ...context.Context) chan V
- func (seq SeqDeque[V]) ChunkBy(fn func(a, b V) bool) SeqSlices[V]
- func (seq SeqDeque[V]) Chunks(n Int) SeqSlices[V]
- func (seq SeqDeque[V]) Collect() *Deque[V]
- func (seq SeqDeque[V]) Combinations(size Int) SeqSlices[V]
- func (seq SeqDeque[V]) Context(ctx context.Context) SeqDeque[V]
- func (seq SeqDeque[V]) Count() Int
- func (seq SeqDeque[V]) CounterBy[K comparable](fn func(V) K) SeqMapOrd[K, Int]
- func (seq SeqDeque[V]) Cycle() SeqDeque[V]
- func (seq SeqDeque[V]) Dedup() SeqDeque[V]
- func (seq SeqDeque[V]) Enumerate() SeqMapOrd[Int, V]
- func (seq SeqDeque[V]) Exclude(fn func(V) bool) SeqDeque[V]
- func (seq SeqDeque[V]) Filter(fn func(V) bool) SeqDeque[V]
- func (seq SeqDeque[V]) FilterMap[U any](fn func(V) Option[U]) SeqDeque[U]
- func (seq SeqDeque[V]) Find(fn func(v V) bool) Option[V]
- func (seq SeqDeque[V]) FindMap[U any](fn func(V) Option[U]) Option[U]
- func (seq SeqDeque[V]) First() Option[V]
- func (seq SeqDeque[V]) FlatMap[U any](fn func(V) SeqDeque[U]) SeqDeque[U]
- func (seq SeqDeque[V]) Flatten() SeqDeque[V]
- func (seq SeqDeque[V]) Fold[A any](init A, fn func(acc A, val V) A) A
- func (seq SeqDeque[V]) ForEach(fn func(v V))
- func (seq SeqDeque[V]) Inspect(fn func(v V)) SeqDeque[V]
- func (seq SeqDeque[V]) Intersperse(sep V) SeqDeque[V]
- func (seq SeqDeque[V]) Last() Option[V]
- func (seq SeqDeque[V]) Map[U any](transform func(V) U) SeqDeque[U]
- func (seq SeqDeque[V]) MaxBy(fn func(V, V) cmp.Ordering) Option[V]
- func (seq SeqDeque[V]) MinBy(fn func(V, V) cmp.Ordering) Option[V]
- func (seq *SeqDeque[V]) Next() Option[V]
- func (seq SeqDeque[V]) Nth(n Int) Option[V]
- func (seq SeqDeque[V]) Partition(fn func(v V) bool) (*Deque[V], *Deque[V])
- func (seq SeqDeque[V]) Permutations() SeqSlices[V]
- func (seq SeqDeque[V]) ProductBy[S constraints.Number](fn func(V) S) S
- func (seq SeqDeque[V]) Pull() (func() (V, bool), func())
- func (seq SeqDeque[V]) Range(fn func(v V) bool)
- func (seq SeqDeque[V]) Reduce(fn func(a, b V) V) Option[V]
- func (seq SeqDeque[V]) Scan[A any](init A, fn func(acc A, val V) A) SeqDeque[A]
- func (seq SeqDeque[V]) Skip(n uint) SeqDeque[V]
- func (seq SeqDeque[V]) SkipWhile(fn func(V) bool) SeqDeque[V]
- func (seq SeqDeque[V]) SortBy(fn func(a, b V) cmp.Ordering) SeqDeque[V]
- func (seq SeqDeque[V]) StepBy(n uint) SeqDeque[V]
- func (seq SeqDeque[V]) SumBy[S constraints.Number](fn func(V) S) S
- func (seq SeqDeque[V]) Take(n uint) SeqDeque[V]
- func (seq SeqDeque[V]) TakeWhile(fn func(V) bool) SeqDeque[V]
- func (seq SeqDeque[V]) TryMap[U any](fn func(V) Result[U]) SeqResult[U]
- func (seq SeqDeque[V]) Unique() SeqDeque[V]
- func (seq SeqDeque[V]) Windows(n Int) SeqSlices[V]
- func (seq SeqDeque[V]) Zip[U any](two SeqDeque[U]) SeqPairs[V, U]
- type SeqHeap
- func (seq SeqHeap[V]) All(fn func(v V) bool) bool
- func (seq SeqHeap[V]) Any(fn func(V) bool) bool
- func (seq SeqHeap[V]) Chain(seqs ...SeqHeap[V]) SeqHeap[V]
- func (seq SeqHeap[V]) Chan(ctxs ...context.Context) chan V
- func (seq SeqHeap[V]) ChunkBy(fn func(a, b V) bool) SeqSlices[V]
- func (seq SeqHeap[V]) Chunks(n Int) SeqSlices[V]
- func (seq SeqHeap[V]) Collect(compareFn func(V, V) cmp.Ordering) *Heap[V]
- func (seq SeqHeap[V]) Combinations(size Int) SeqSlices[V]
- func (seq SeqHeap[V]) Context(ctx context.Context) SeqHeap[V]
- func (seq SeqHeap[V]) Count() Int
- func (seq SeqHeap[V]) CounterBy[K comparable](fn func(V) K) SeqMapOrd[K, Int]
- func (seq SeqHeap[V]) Cycle() SeqHeap[V]
- func (seq SeqHeap[V]) Dedup() SeqHeap[V]
- func (seq SeqHeap[V]) Enumerate() SeqMapOrd[Int, V]
- func (seq SeqHeap[V]) Exclude(fn func(V) bool) SeqHeap[V]
- func (seq SeqHeap[V]) Filter(fn func(V) bool) SeqHeap[V]
- func (seq SeqHeap[V]) FilterMap[U any](fn func(V) Option[U]) SeqHeap[U]
- func (seq SeqHeap[V]) Find(fn func(v V) bool) Option[V]
- func (seq SeqHeap[V]) FindMap[U any](fn func(V) Option[U]) Option[U]
- func (seq SeqHeap[V]) First() Option[V]
- func (seq SeqHeap[V]) FlatMap[U any](fn func(V) SeqHeap[U]) SeqHeap[U]
- func (seq SeqHeap[V]) Flatten() SeqHeap[V]
- func (seq SeqHeap[V]) Fold[A any](init A, fn func(acc A, val V) A) A
- func (seq SeqHeap[V]) ForEach(fn func(v V))
- func (seq SeqHeap[V]) Inspect(fn func(v V)) SeqHeap[V]
- func (seq SeqHeap[V]) Intersperse(sep V) SeqHeap[V]
- func (seq SeqHeap[V]) Last() Option[V]
- func (seq SeqHeap[V]) Map[U any](transform func(V) U) SeqHeap[U]
- func (seq SeqHeap[V]) MaxBy(fn func(V, V) cmp.Ordering) Option[V]
- func (seq SeqHeap[V]) MinBy(fn func(V, V) cmp.Ordering) Option[V]
- func (seq *SeqHeap[V]) Next() Option[V]
- func (seq SeqHeap[V]) Nth(n Int) Option[V]
- func (seq SeqHeap[V]) Partition(fn func(v V) bool, leftCmp, rightCmp func(V, V) cmp.Ordering) (*Heap[V], *Heap[V])
- func (seq SeqHeap[V]) Permutations() SeqSlices[V]
- func (seq SeqHeap[V]) ProductBy[S constraints.Number](fn func(V) S) S
- func (seq SeqHeap[V]) Pull() (func() (V, bool), func())
- func (seq SeqHeap[V]) Range(fn func(v V) bool)
- func (seq SeqHeap[V]) Reduce(fn func(a, b V) V) Option[V]
- func (seq SeqHeap[V]) Scan[A any](init A, fn func(acc A, val V) A) SeqHeap[A]
- func (seq SeqHeap[V]) Skip(n uint) SeqHeap[V]
- func (seq SeqHeap[V]) SkipWhile(fn func(V) bool) SeqHeap[V]
- func (seq SeqHeap[V]) SortBy(fn func(a, b V) cmp.Ordering) SeqHeap[V]
- func (seq SeqHeap[V]) StepBy(n uint) SeqHeap[V]
- func (seq SeqHeap[V]) SumBy[S constraints.Number](fn func(V) S) S
- func (seq SeqHeap[V]) Take(n uint) SeqHeap[V]
- func (seq SeqHeap[V]) TakeWhile(fn func(V) bool) SeqHeap[V]
- func (seq SeqHeap[V]) TryMap[U any](fn func(V) Result[U]) SeqResult[U]
- func (seq SeqHeap[V]) Unique() SeqHeap[V]
- func (seq SeqHeap[V]) Windows(n Int) SeqSlices[V]
- func (seq SeqHeap[V]) Zip[U any](two SeqHeap[U]) SeqPairs[V, U]
- type SeqMap
- func (seq SeqMap[K, V]) All(fn func(K, V) bool) bool
- func (seq SeqMap[K, V]) Any(fn func(K, V) bool) bool
- func (seq SeqMap[K, V]) Chain(seqs ...SeqMap[K, V]) SeqMap[K, V]
- func (seq SeqMap[K, V]) Chan(ctxs ...context.Context) chan Pair[K, V]
- func (seq SeqMap[K, V]) Collect() Map[K, V]
- func (seq SeqMap[K, V]) Context(ctx context.Context) SeqMap[K, V]
- func (seq SeqMap[K, V]) Count() Int
- func (seq SeqMap[K, V]) Exclude(fn func(K, V) bool) SeqMap[K, V]
- func (seq SeqMap[K, V]) Filter(fn func(K, V) bool) SeqMap[K, V]
- func (seq SeqMap[K, V]) FilterByKey(fn func(K) bool) SeqMap[K, V]
- func (seq SeqMap[K, V]) FilterByValue(fn func(V) bool) SeqMap[K, V]
- func (seq SeqMap[K, V]) FilterMap[K2 comparable, V2 any](fn func(K, V) Option[Pair[K2, V2]]) SeqMap[K2, V2]
- func (seq SeqMap[K, V]) Find(fn func(k K, v V) bool) Option[Pair[K, V]]
- func (seq SeqMap[K, V]) FindMap[U any](fn func(K, V) Option[U]) Option[U]
- func (seq SeqMap[K, V]) First() Option[Pair[K, V]]
- func (seq SeqMap[K, V]) Fold[A any](init A, fn func(acc A, k K, v V) A) A
- func (seq SeqMap[K, V]) ForEach(fn func(k K, v V))
- func (seq SeqMap[K, V]) Inspect(fn func(k K, v V)) SeqMap[K, V]
- func (seq SeqMap[K, V]) Keys() SeqSlice[K]
- func (seq SeqMap[K, V]) Last() Option[Pair[K, V]]
- func (seq SeqMap[K, V]) Map[K2 comparable, V2 any](transform func(K, V) (K2, V2)) SeqMap[K2, V2]
- func (seq *SeqMap[K, V]) Next() Option[Pair[K, V]]
- func (seq SeqMap[K, V]) Nth(n Int) Option[Pair[K, V]]
- func (seq SeqMap[K, V]) ProductBy[S constraints.Number](fn func(K, V) S) S
- func (seq SeqMap[K, V]) Pull() (func() (K, V, bool), func())
- func (seq SeqMap[K, V]) Range(fn func(k K, v V) bool)
- func (seq SeqMap[K, V]) Skip(n uint) SeqMap[K, V]
- func (seq SeqMap[K, V]) SkipWhile(fn func(K, V) bool) SeqMap[K, V]
- func (seq SeqMap[K, V]) StepBy(n uint) SeqMap[K, V]
- func (seq SeqMap[K, V]) SumBy[S constraints.Number](fn func(K, V) S) S
- func (seq SeqMap[K, V]) Take(n uint) SeqMap[K, V]
- func (seq SeqMap[K, V]) TakeWhile(fn func(K, V) bool) SeqMap[K, V]
- func (seq SeqMap[K, V]) TryMap[U any](fn func(K, V) Result[U]) SeqResult[U]
- func (seq SeqMap[K, V]) Values() SeqSlice[V]
- type SeqMapOrd
- func (seq SeqMapOrd[K, V]) All(fn func(K, V) bool) bool
- func (seq SeqMapOrd[K, V]) Any(fn func(K, V) bool) bool
- func (seq SeqMapOrd[K, V]) Chain(seqs ...SeqMapOrd[K, V]) SeqMapOrd[K, V]
- func (seq SeqMapOrd[K, V]) Chan(ctxs ...context.Context) chan Pair[K, V]
- func (seq SeqMapOrd[K, V]) Collect() MapOrd[K, V]
- func (seq SeqMapOrd[K, V]) Context(ctx context.Context) SeqMapOrd[K, V]
- func (seq SeqMapOrd[K, V]) Count() Int
- func (seq SeqMapOrd[K, V]) Exclude(fn func(K, V) bool) SeqMapOrd[K, V]
- func (seq SeqMapOrd[K, V]) Filter(fn func(K, V) bool) SeqMapOrd[K, V]
- func (seq SeqMapOrd[K, V]) FilterByKey(fn func(K) bool) SeqMapOrd[K, V]
- func (seq SeqMapOrd[K, V]) FilterByValue(fn func(V) bool) SeqMapOrd[K, V]
- func (seq SeqMapOrd[K, V]) FilterMap[K2 comparable, V2 any](fn func(K, V) Option[Pair[K2, V2]]) SeqMapOrd[K2, V2]
- func (seq SeqMapOrd[K, V]) Find(fn func(k K, v V) bool) Option[Pair[K, V]]
- func (seq SeqMapOrd[K, V]) FindMap[U any](fn func(K, V) Option[U]) Option[U]
- func (seq SeqMapOrd[K, V]) First() Option[Pair[K, V]]
- func (seq SeqMapOrd[K, V]) Fold[A any](init A, fn func(acc A, k K, v V) A) A
- func (seq SeqMapOrd[K, V]) ForEach(fn func(k K, v V))
- func (seq SeqMapOrd[K, V]) Inspect(fn func(k K, v V)) SeqMapOrd[K, V]
- func (seq SeqMapOrd[K, V]) Keys() SeqSlice[K]
- func (seq SeqMapOrd[K, V]) Last() Option[Pair[K, V]]
- func (seq SeqMapOrd[K, V]) Map[K2 comparable, V2 any](transform func(K, V) (K2, V2)) SeqMapOrd[K2, V2]
- func (seq *SeqMapOrd[K, V]) Next() Option[Pair[K, V]]
- func (seq SeqMapOrd[K, V]) Nth(n Int) Option[Pair[K, V]]
- func (seq SeqMapOrd[K, V]) ProductBy[S constraints.Number](fn func(K, V) S) S
- func (seq SeqMapOrd[K, V]) Pull() (func() (K, V, bool), func())
- func (seq SeqMapOrd[K, V]) Range(fn func(k K, v V) bool)
- func (seq SeqMapOrd[K, V]) Skip(n uint) SeqMapOrd[K, V]
- func (seq SeqMapOrd[K, V]) SkipWhile(fn func(K, V) bool) SeqMapOrd[K, V]
- func (seq SeqMapOrd[K, V]) SortBy(fn func(a, b Pair[K, V]) cmp.Ordering) SeqMapOrd[K, V]
- func (seq SeqMapOrd[K, V]) SortByKey(fn func(a, b K) cmp.Ordering) SeqMapOrd[K, V]
- func (seq SeqMapOrd[K, V]) SortByValue(fn func(a, b V) cmp.Ordering) SeqMapOrd[K, V]
- func (seq SeqMapOrd[K, V]) StepBy(n uint) SeqMapOrd[K, V]
- func (seq SeqMapOrd[K, V]) SumBy[S constraints.Number](fn func(K, V) S) S
- func (seq SeqMapOrd[K, V]) Take(n uint) SeqMapOrd[K, V]
- func (seq SeqMapOrd[K, V]) TakeWhile(fn func(K, V) bool) SeqMapOrd[K, V]
- func (seq SeqMapOrd[K, V]) TryMap[U any](fn func(K, V) Result[U]) SeqResult[U]
- func (seq SeqMapOrd[K, V]) Unzip() (Slice[K], Slice[V])
- func (seq SeqMapOrd[K, V]) Values() SeqSlice[V]
- type SeqPairs
- func (seq SeqPairs[K, V]) All(fn func(K, V) bool) bool
- func (seq SeqPairs[K, V]) Any(fn func(K, V) bool) bool
- func (seq SeqPairs[K, V]) Collect() []Pair[K, V]
- func (seq SeqPairs[K, V]) Count() Int
- func (seq SeqPairs[K, V]) Exclude(fn func(K, V) bool) SeqPairs[K, V]
- func (seq SeqPairs[K, V]) Filter(fn func(K, V) bool) SeqPairs[K, V]
- func (seq SeqPairs[K, V]) FilterByKey(fn func(K) bool) SeqPairs[K, V]
- func (seq SeqPairs[K, V]) FilterByValue(fn func(V) bool) SeqPairs[K, V]
- func (seq SeqPairs[K, V]) Find(fn func(K, V) bool) Option[Pair[K, V]]
- func (seq SeqPairs[K, V]) FindMap[U any](fn func(K, V) Option[U]) Option[U]
- func (seq SeqPairs[K, V]) Fold[A any](init A, fn func(acc A, k K, v V) A) A
- func (seq SeqPairs[K, V]) ForEach(fn func(K, V))
- func (seq SeqPairs[K, V]) Inspect(fn func(K, V)) SeqPairs[K, V]
- func (seq SeqPairs[K, V]) Keys() SeqSlice[K]
- func (seq SeqPairs[K, V]) Map[T any](fn func(K, V) T) SeqSlice[T]
- func (seq SeqPairs[K, V]) ProductBy[S constraints.Number](fn func(K, V) S) S
- func (seq SeqPairs[K, V]) Skip(n uint) SeqPairs[K, V]
- func (seq SeqPairs[K, V]) SkipWhile(fn func(K, V) bool) SeqPairs[K, V]
- func (seq SeqPairs[K, V]) SumBy[S constraints.Number](fn func(K, V) S) S
- func (seq SeqPairs[K, V]) Take(n uint) SeqPairs[K, V]
- func (seq SeqPairs[K, V]) TakeWhile(fn func(K, V) bool) SeqPairs[K, V]
- func (seq SeqPairs[K, V]) TryMap[U any](fn func(K, V) Result[U]) SeqResult[U]
- func (seq SeqPairs[K, V]) Unzip() (Slice[K], Slice[V])
- func (seq SeqPairs[K, V]) Values() SeqSlice[V]
- type SeqResult
- func (seq SeqResult[V]) All(fn func(v V) bool) Result[bool]
- func (seq SeqResult[V]) Any(fn func(v V) bool) Result[bool]
- func (seq SeqResult[V]) Chain(seqs ...SeqResult[V]) SeqResult[V]
- func (seq SeqResult[V]) Collect() Slice[Result[V]]
- func (seq SeqResult[V]) Context(ctx context.Context) SeqResult[V]
- func (seq SeqResult[V]) Count() Int
- func (seq SeqResult[V]) CounterBy[K comparable](fn func(V) K) Result[MapOrd[K, Int]]
- func (seq SeqResult[V]) Dedup() SeqResult[V]
- func (seq SeqResult[V]) Err() SeqSlice[error]
- func (seq SeqResult[V]) Exclude(fn func(V) bool) SeqResult[V]
- func (seq SeqResult[V]) Filter(fn func(V) bool) SeqResult[V]
- func (seq SeqResult[V]) FilterMap[U any](fn func(V) Option[U]) SeqResult[U]
- func (seq SeqResult[V]) Find(fn func(V) bool) Result[Option[V]]
- func (seq SeqResult[V]) FindMap[U any](fn func(V) Option[U]) Result[Option[U]]
- func (seq SeqResult[V]) First() Result[Option[V]]
- func (seq SeqResult[V]) FirstErr() Option[error]
- func (seq SeqResult[V]) FlatMap[U any](fn func(V) SeqSlice[U]) SeqResult[U]
- func (seq SeqResult[V]) Flatten() SeqResult[V]
- func (seq SeqResult[V]) Fold[A any](init A, fn func(acc A, val V) A) Result[A]
- func (seq SeqResult[V]) ForEach(fn func(v Result[V]))
- func (seq SeqResult[V]) Inspect(fn func(v V)) SeqResult[V]
- func (seq SeqResult[V]) Intersperse(sep V) SeqResult[V]
- func (seq SeqResult[V]) Last() Result[Option[V]]
- func (seq SeqResult[V]) Map[U any](transform func(V) U) SeqResult[U]
- func (seq SeqResult[V]) MaxBy(fn func(V, V) cmp.Ordering) Result[Option[V]]
- func (seq SeqResult[V]) MinBy(fn func(V, V) cmp.Ordering) Result[Option[V]]
- func (seq *SeqResult[V]) Next() Option[Result[V]]
- func (seq SeqResult[V]) Nth(n Int) Result[Option[V]]
- func (seq SeqResult[V]) Ok() SeqSlice[V]
- func (seq SeqResult[V]) Partition() (Slice[V], Slice[error])
- func (seq SeqResult[V]) ProductBy[S constraints.Number](fn func(V) S) Result[S]
- func (seq SeqResult[V]) Pull() (func() (Result[V], bool), func())
- func (seq SeqResult[V]) Range(fn func(v Result[V]) bool)
- func (seq SeqResult[V]) Reduce(fn func(a, b V) V) Result[Option[V]]
- func (seq SeqResult[V]) Scan[A any](init A, fn func(acc A, val V) A) SeqResult[A]
- func (seq SeqResult[V]) Skip(n uint) SeqResult[V]
- func (seq SeqResult[V]) SkipWhile(fn func(V) bool) SeqResult[V]
- func (seq SeqResult[V]) SortBy(fn func(a, b V) cmp.Ordering) SeqResult[V]
- func (seq SeqResult[V]) StepBy(n uint) SeqResult[V]
- func (seq SeqResult[V]) SumBy[S constraints.Number](fn func(V) S) Result[S]
- func (seq SeqResult[V]) Take(n uint) SeqResult[V]
- func (seq SeqResult[V]) TakeWhile(fn func(V) bool) SeqResult[V]
- func (seq SeqResult[V]) TryCollect() Result[Slice[V]]
- func (seq SeqResult[V]) Unique() SeqResult[V]
- type SeqSet
- func (seq SeqSet[V]) All(fn func(v V) bool) bool
- func (seq SeqSet[V]) Any(fn func(V) bool) bool
- func (seq SeqSet[V]) Chain(seqs ...SeqSet[V]) SeqSet[V]
- func (seq SeqSet[V]) Chan(ctxs ...context.Context) chan V
- func (seq SeqSet[V]) Collect() Set[V]
- func (seq SeqSet[V]) Context(ctx context.Context) SeqSet[V]
- func (seq SeqSet[V]) Count() Int
- func (seq SeqSet[V]) CounterBy[K comparable](fn func(V) K) SeqMapOrd[K, Int]
- func (seq SeqSet[V]) Difference(other Set[V]) SeqSet[V]
- func (seq SeqSet[V]) Exclude(fn func(V) bool) SeqSet[V]
- func (seq SeqSet[V]) Filter(fn func(V) bool) SeqSet[V]
- func (seq SeqSet[V]) FilterMap[U comparable](fn func(V) Option[U]) SeqSet[U]
- func (seq SeqSet[V]) Find(fn func(v V) bool) Option[V]
- func (seq SeqSet[V]) FindMap[U any](fn func(V) Option[U]) Option[U]
- func (seq SeqSet[V]) First() Option[V]
- func (seq SeqSet[V]) Fold[A any](init A, fn func(acc A, val V) A) A
- func (seq SeqSet[V]) ForEach(fn func(v V))
- func (seq SeqSet[V]) Inspect(fn func(v V)) SeqSet[V]
- func (seq SeqSet[V]) Intersection(other Set[V]) SeqSet[V]
- func (seq SeqSet[V]) Last() Option[V]
- func (seq SeqSet[V]) Map[U comparable](transform func(V) U) SeqSet[U]
- func (seq SeqSet[V]) MaxBy(fn func(V, V) cmp.Ordering) Option[V]
- func (seq SeqSet[V]) MinBy(fn func(V, V) cmp.Ordering) Option[V]
- func (seq *SeqSet[V]) Next() Option[V]
- func (seq SeqSet[V]) Nth(n Int) Option[V]
- func (seq SeqSet[V]) Partition(fn func(V) bool) (Set[V], Set[V])
- func (seq SeqSet[V]) ProductBy[S constraints.Number](fn func(V) S) S
- func (seq SeqSet[V]) Pull() (func() (V, bool), func())
- func (seq SeqSet[V]) Range(fn func(v V) bool)
- func (seq SeqSet[V]) Reduce(fn func(a, b V) V) Option[V]
- func (seq SeqSet[V]) Skip(n uint) SeqSet[V]
- func (seq SeqSet[V]) SkipWhile(fn func(V) bool) SeqSet[V]
- func (seq SeqSet[V]) StepBy(n uint) SeqSet[V]
- func (seq SeqSet[V]) SumBy[S constraints.Number](fn func(V) S) S
- func (seq SeqSet[V]) Take(n uint) SeqSet[V]
- func (seq SeqSet[V]) TakeWhile(fn func(V) bool) SeqSet[V]
- func (seq SeqSet[V]) TryMap[U any](fn func(V) Result[U]) SeqResult[U]
- type SeqSlice
- func (seq SeqSlice[V]) All(fn func(v V) bool) bool
- func (seq SeqSlice[V]) Any(fn func(V) bool) bool
- func (seq SeqSlice[V]) Chain(seqs ...SeqSlice[V]) SeqSlice[V]
- func (seq SeqSlice[V]) Chan(ctxs ...context.Context) chan V
- func (seq SeqSlice[V]) ChunkBy(fn func(a, b V) bool) SeqSlices[V]
- func (seq SeqSlice[V]) Chunks(n Int) SeqSlices[V]
- func (seq SeqSlice[V]) Collect() Slice[V]
- func (seq SeqSlice[V]) Combinations(size Int) SeqSlices[V]
- func (seq SeqSlice[V]) Context(ctx context.Context) SeqSlice[V]
- func (seq SeqSlice[V]) Count() Int
- func (seq SeqSlice[V]) CounterBy[K comparable](fn func(V) K) SeqMapOrd[K, Int]
- func (seq SeqSlice[V]) Cycle() SeqSlice[V]
- func (seq SeqSlice[V]) Dedup() SeqSlice[V]
- func (seq SeqSlice[V]) Enumerate() SeqMapOrd[Int, V]
- func (seq SeqSlice[V]) Exclude(fn func(V) bool) SeqSlice[V]
- func (seq SeqSlice[V]) Filter(fn func(V) bool) SeqSlice[V]
- func (seq SeqSlice[V]) FilterMap[U any](fn func(V) Option[U]) SeqSlice[U]
- func (seq SeqSlice[V]) Find(fn func(v V) bool) Option[V]
- func (seq SeqSlice[V]) FindMap[U any](fn func(V) Option[U]) Option[U]
- func (seq SeqSlice[V]) First() Option[V]
- func (seq SeqSlice[V]) FlatMap[U any](fn func(V) SeqSlice[U]) SeqSlice[U]
- func (seq SeqSlice[V]) Flatten() SeqSlice[V]
- func (seq SeqSlice[V]) Fold[A any](init A, fn func(acc A, val V) A) A
- func (seq SeqSlice[V]) ForEach(fn func(v V))
- func (seq SeqSlice[V]) Inspect(fn func(v V)) SeqSlice[V]
- func (seq SeqSlice[V]) Intersperse(sep V) SeqSlice[V]
- func (seq SeqSlice[V]) Last() Option[V]
- func (seq SeqSlice[V]) Map[U any](transform func(V) U) SeqSlice[U]
- func (seq SeqSlice[V]) MaxBy(fn func(V, V) cmp.Ordering) Option[V]
- func (seq SeqSlice[V]) MinBy(fn func(V, V) cmp.Ordering) Option[V]
- func (seq *SeqSlice[V]) Next() Option[V]
- func (seq SeqSlice[V]) Nth(n Int) Option[V]
- func (seq SeqSlice[V]) Partition(fn func(v V) bool) (Slice[V], Slice[V])
- func (seq SeqSlice[V]) Permutations() SeqSlices[V]
- func (seq SeqSlice[V]) ProductBy[S constraints.Number](fn func(V) S) S
- func (seq SeqSlice[V]) Pull() (func() (V, bool), func())
- func (seq SeqSlice[V]) Range(fn func(v V) bool)
- func (seq SeqSlice[V]) Reduce(fn func(a, b V) V) Option[V]
- func (seq SeqSlice[V]) Scan[A any](init A, fn func(acc A, val V) A) SeqSlice[A]
- func (seq SeqSlice[V]) Skip(n uint) SeqSlice[V]
- func (seq SeqSlice[V]) SkipWhile(fn func(V) bool) SeqSlice[V]
- func (seq SeqSlice[V]) SortBy(fn func(a, b V) cmp.Ordering) SeqSlice[V]
- func (seq SeqSlice[V]) StepBy(n uint) SeqSlice[V]
- func (seq SeqSlice[V]) SumBy[S constraints.Number](fn func(V) S) S
- func (seq SeqSlice[V]) Take(n uint) SeqSlice[V]
- func (seq SeqSlice[V]) TakeWhile(fn func(V) bool) SeqSlice[V]
- func (seq SeqSlice[V]) TryMap[U any](fn func(V) Result[U]) SeqResult[U]
- func (seq SeqSlice[V]) Unique() SeqSlice[V]
- func (seq SeqSlice[V]) Windows(n Int) SeqSlices[V]
- func (seq SeqSlice[V]) Zip[U any](two SeqSlice[U]) SeqPairs[V, U]
- type SeqSlices
- type Set
- func (s Set[T]) Clear()
- func (s Set[T]) Clone() Set[T]
- func (s Set[T]) Contains(v T) bool
- func (s Set[T]) ContainsAll(other Set[T]) bool
- func (s Set[T]) ContainsAny(other Set[T]) bool
- func (s Set[T]) Difference(other Set[T]) SeqSet[T]
- func (s Set[T]) Disjoint(other Set[T]) bool
- func (s Set[T]) Eq(other Set[T]) bool
- func (s Set[T]) Insert(values ...T)
- func (s Set[T]) Intersection(other Set[T]) SeqSet[T]
- func (s Set[T]) IsEmpty() bool
- func (s Set[T]) Iter() SeqSet[T]
- func (s Set[T]) Len() Int
- func (s Set[T]) Ne(other Set[T]) bool
- func (s Set[T]) Print() Set[T]
- func (s Set[T]) Println() Set[T]
- func (s Set[T]) Remove(v T) bool
- func (s Set[T]) Slice() Slice[T]
- func (s Set[T]) String() string
- func (s Set[T]) Subset(other Set[T]) bool
- func (s Set[T]) Superset(other Set[T]) bool
- func (s Set[T]) SymmetricDifference(other Set[T]) SeqSet[T]
- func (s Set[T]) Transform[U any](fn func(Set[T]) U) U
- func (s Set[T]) Union(other Set[T]) SeqSet[T]
- type Slice
- func (sl Slice[T]) Append(elems ...T) Slice[T]
- func (sl Slice[T]) AppendUnique(elems ...T) Slice[T]
- func (sl Slice[T]) BinarySearch(value T, fn func(a, b T) cmp.Ordering) Option[Int]
- func (sl Slice[T]) Cap() Int
- func (sl Slice[T]) Clip() Slice[T]
- func (sl Slice[T]) Clone() Slice[T]
- func (sl Slice[T]) Contains(val T) bool
- func (sl Slice[T]) ContainsAll(values ...T) bool
- func (sl Slice[T]) ContainsAny(values ...T) bool
- func (sl Slice[T]) ContainsBy(fn func(t T) bool) bool
- func (sl *Slice[T]) DedupBy(eq func(a, b T) bool)
- func (sl Slice[T]) Eq(other Slice[T]) bool
- func (sl Slice[T]) EqBy(other Slice[T], fn func(x, y T) bool) bool
- func (sl Slice[T]) Fill(val T)
- func (sl Slice[T]) First() Option[T]
- func (sl Slice[T]) Get(index Int) Option[T]
- func (sl Slice[T]) Grow(n Int) Slice[T]
- func (sl Slice[T]) Heap(compareFn func(T, T) cmp.Ordering) *Heap[T]
- func (sl Slice[T]) Index(val T) Int
- func (sl Slice[T]) IndexBy(fn func(t T) bool) Int
- func (sl *Slice[T]) Insert(i Int, values ...T)
- func (sl Slice[T]) IsEmpty() bool
- func (sl Slice[T]) IsSortedBy(fn func(a, b T) cmp.Ordering) bool
- func (sl Slice[T]) Iter() SeqSlice[T]
- func (sl Slice[T]) IterReverse() SeqSlice[T]
- func (sl Slice[T]) Join(sep ...T) String
- func (sl Slice[T]) Last() Option[T]
- func (sl Slice[T]) LastIndex() Int
- func (sl Slice[T]) Len() Int
- func (sl Slice[T]) Ne(other Slice[T]) bool
- func (sl Slice[T]) NeBy(other Slice[T], fn func(x, y T) bool) bool
- func (sl Slice[T]) PartitionPoint(pred func(T) bool) Int
- func (sl *Slice[T]) Pop() Option[T]
- func (sl Slice[T]) Print() Slice[T]
- func (sl Slice[T]) Println() Slice[T]
- func (sl *Slice[T]) Push(elems ...T)
- func (sl *Slice[T]) PushUnique(elems ...T)
- func (sl Slice[T]) Random() T
- func (sl Slice[T]) RandomRange(from, to Int) Slice[T]
- func (sl Slice[T]) RandomSample(sequence Int) Slice[T]
- func (sl *Slice[T]) Remove(index Int) Option[T]
- func (sl *Slice[T]) Replace(i, j Int, values ...T)
- func (sl *Slice[T]) Retain(fn func(T) bool)
- func (sl Slice[T]) Reverse()
- func (sl Slice[T]) Set(index Int, val T) Option[T]
- func (sl Slice[T]) Shuffle()
- func (sl Slice[T]) SortBy(fn func(a, b T) cmp.Ordering)
- func (sl Slice[T]) Std() []T
- func (sl Slice[T]) String() string
- func (sl Slice[T]) SubSlice(start, end Int, step ...Int) Slice[T]
- func (sl Slice[T]) Swap(i, j Int)
- func (sl Slice[T]) Transform[U any](fn func(Slice[T]) U) U
- func (sl Slice[T]) Unpack(vars ...*T)
- type String
- func (s String) Append(str String) String
- func (s String) Builder() *Builder
- func (s String) Bytes() Bytes
- func (s String) BytesUnsafe() Bytes
- func (s String) Center(length Int, pad String) String
- func (s String) Chars() SeqSlice[String]
- func (s String) Chunks(size Int) SeqSlice[String]
- func (s String) Clone() String
- func (s String) Cmp(str String) cmp.Ordering
- func (s String) Compress() compress
- func (s String) Contains(substr String) bool
- func (s String) ContainsAll(substrs ...String) bool
- func (s String) ContainsAny(substrs ...String) bool
- func (s String) ContainsAnyChars(chars String) bool
- func (s String) ContainsRune(r rune) bool
- func (s String) Count(substr String) Int
- func (s String) Cut(start, end String, rmtags ...bool) (String, String)
- func (s String) Decode() decode
- func (s String) Decompress() decompress
- func (s String) Encode() encode
- func (s String) EndsWith(suffix String) bool
- func (s String) EndsWithAny(suffixes ...String) bool
- func (s String) Eq(str String) bool
- func (s String) EqFold(str String) bool
- func (s String) Fields() SeqSlice[String]
- func (s String) FieldsBy(fn func(r rune) bool) SeqSlice[String]
- func (s String) Format(template String) String
- func (s String) Gt(str String) bool
- func (s String) Gte(str String) bool
- func (s String) Hash() shash
- func (s String) Index(substr String) Int
- func (s String) IndexRune(r rune) Int
- func (s String) IsASCII() bool
- func (s String) IsDigit() bool
- func (s String) IsEmpty() bool
- func (s String) IsLower() bool
- func (s String) IsTitle() bool
- func (s String) IsUpper() bool
- func (s String) LastIndex(substr String) Int
- func (s String) LeftJustify(length Int, pad String) String
- func (s String) Len() Int
- func (s String) LenRunes() Int
- func (s String) Lines() SeqSlice[String]
- func (s String) Lower() String
- func (s String) Lt(str String) bool
- func (s String) Lte(str String) bool
- func (s String) Map(fn func(rune) rune) String
- func (s String) Max(b ...String) String
- func (s String) Min(b ...String) String
- func (s String) Ne(str String) bool
- func (s String) NormalizeNFC() String
- func (s String) Prepend(str String) String
- func (s String) Print() String
- func (s String) Println() String
- func (String) Random(length Int, letters ...String) String
- func (s String) Reader() *strings.Reader
- func (s String) Regexp() regexps
- func (s String) Remove(matches ...String) String
- func (s String) Repeat(count Int) String
- func (s String) Replace(oldS, newS String, n Int) String
- func (s String) ReplaceAll(oldS, newS String) String
- func (s String) ReplaceMulti(oldnew ...String) String
- func (s String) ReplaceNth(oldS, newS String, n Int) String
- func (s String) Reverse() String
- func (s String) RightJustify(length Int, pad String) String
- func (s String) Runes() Slice[rune]
- func (s *String) Scan(src any) error
- func (s String) Similarity(str String) Float
- func (s String) Split(sep String) SeqSlice[String]
- func (s String) SplitAfter(sep String) SeqSlice[String]
- func (s String) SplitN(sep String, n Int) Slice[String]
- func (s String) StartsWith(prefix String) bool
- func (s String) StartsWithAny(prefixes ...String) bool
- func (s String) Std() string
- func (s String) StripPrefix(prefix String) String
- func (s String) StripSuffix(suffix String) String
- func (s String) SubString(start, end Int, step ...Int) String
- func (s String) Title() String
- func (s String) Transform[U any](fn func(String) U) U
- func (s String) Trim() String
- func (s String) TrimEnd() String
- func (s String) TrimEndSet(cutset String) String
- func (s String) TrimSet(cutset String) String
- func (s String) TrimStart() String
- func (s String) TrimStartSet(cutset String) String
- func (s String) Truncate(max Int) String
- func (s String) TryBigInt() Result[*big.Int]
- func (s String) TryBool() Result[bool]
- func (s String) TryComplex() Result[complex128]
- func (s String) TryFloat() Result[Float]
- func (s String) TryInt() Result[Int]
- func (s String) TryUint() Result[uint]
- func (s String) Upper() String
- func (s String) Value() (driver.Value, error)
- type Unit
- type VacantEntry
- func (e VacantEntry[K, V]) AndModify(fn func(*V)) Entry[K, V]
- func (e VacantEntry[K, V]) Insert(value V) V
- func (e VacantEntry[K, V]) Key() K
- func (e VacantEntry[K, V]) OrDefault() V
- func (e VacantEntry[K, V]) OrInsert(value V) V
- func (e VacantEntry[K, V]) OrInsertWith(fn func() V) V
- func (e VacantEntry[K, V]) OrInsertWithKey(fn func(K) V) V
- type VacantOrdEntry
- func (e VacantOrdEntry[K, V]) AndModify(fn func(*V)) OrdEntry[K, V]
- func (e VacantOrdEntry[K, V]) Insert(value V) V
- func (e VacantOrdEntry[K, V]) Key() K
- func (e VacantOrdEntry[K, V]) OrDefault() V
- func (e VacantOrdEntry[K, V]) OrInsert(value V) V
- func (e VacantOrdEntry[K, V]) OrInsertWith(fn func() V) V
- func (e VacantOrdEntry[K, V]) OrInsertWithKey(fn func(K) V) V
- type VacantSafeEntry
- func (e VacantSafeEntry[K, V]) AndModify(fn func(*V)) SafeEntry[K, V]
- func (e VacantSafeEntry[K, V]) Insert(value V) V
- func (e VacantSafeEntry[K, V]) Key() K
- func (e VacantSafeEntry[K, V]) OrDefault() V
- func (e VacantSafeEntry[K, V]) OrInsert(value V) V
- func (e VacantSafeEntry[K, V]) OrInsertWith(fn func() V) V
- func (e VacantSafeEntry[K, V]) OrInsertWithKey(fn func(K) V) V
Constants ¶
const ( // ASCII_LETTERS is the set of all ASCII letters (lowercase + uppercase). ASCII_LETTERS String = ASCII_LOWERCASE + ASCII_UPPERCASE // ASCII_LOWERCASE is the set of lowercase ASCII letters. ASCII_LOWERCASE String = "abcdefghijklmnopqrstuvwxyz" // ASCII_UPPERCASE is the set of uppercase ASCII letters. ASCII_UPPERCASE String = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" // DIGITS is the set of decimal digit characters. DIGITS String = "0123456789" // HEXDIGITS is the set of hexadecimal digit characters (both cases). HEXDIGITS String = "0123456789abcdefABCDEF" // OCTDIGITS is the set of octal digit characters. OCTDIGITS String = "01234567" // PUNCTUATION is the set of ASCII punctuation characters. PUNCTUATION String = `!"#$%&'()*+,-./:;<=>?@[\]^{|}~` + "`" // FileDefault is the default permission mode (0o644) used when writing files. FileDefault os.FileMode = 0o644 // FileCreate is the permission mode (0o666) used when creating files. FileCreate os.FileMode = 0o666 // DirDefault is the default permission mode (0o755) used when creating directories. DirDefault os.FileMode = 0o755 // FullAccess is the permission mode (0o777) granting read, write and execute to everyone. FullAccess os.FileMode = 0o777 // PathSeparator is the OS-specific path separator as a String. PathSeparator = String(os.PathSeparator) )
Variables ¶
var ( // ErrInvalidBinaryLength is returned by binary decoding when the input length is not a multiple of 8. ErrInvalidBinaryLength = errors.New("binary string length must be multiple of 8") // ErrInvalidBinaryDigit is returned by binary decoding when the input contains characters other than '0' and '1'. ErrInvalidBinaryDigit = errors.New("binary string must contain only '0' and '1'") // ErrParseInt is returned when a String cannot be parsed as an integer. ErrParseInt = errors.New("invalid integer") // ErrParseBigInt is returned when a String cannot be parsed as a big integer. ErrParseBigInt = errors.New("invalid big integer") // ErrParseFloat is returned when a String cannot be parsed as a float. ErrParseFloat = errors.New("invalid float") // ErrParseBool is returned when a String cannot be parsed as a bool. ErrParseBool = errors.New("invalid bool") // ErrParseUint is returned when a String cannot be parsed as an unsigned integer. ErrParseUint = errors.New("invalid unsigned integer") // ErrParseComplex is returned when a String cannot be parsed as a complex number. ErrParseComplex = errors.New("invalid complex number") )
Functions ¶
func Errorf ¶ added in v1.0.146
Errorf formats according to a format specifier and returns it as an error. If any argument is referenced via the {:w} format verb, it is both displayed and wrapped into the returned error, making errors.Is and errors.As work through the chain. Multiple {:w} references wrap multiple errors (Go 1.20+).
Example:
err := g.Errorf("could not open {1}: {2:w}", filename, err)
errors.Is(err, os.ErrNotExist) // true
Types ¶
type Builder ¶ added in v1.0.62
type Builder struct {
// contains filtered or unexported fields
}
Builder wraps strings.Builder and provides additional type-safe methods for use with the custom types String and Int.
func NewBuilder ¶ added in v1.0.62
func NewBuilder() *Builder
NewBuilder creates a new instance of Builder.
func (*Builder) Reset ¶ added in v1.0.62
func (b *Builder) Reset()
Reset clears the contents of the builder.
func (*Builder) String ¶ added in v1.0.62
String returns the accumulated string as a custom String type.
type Bytes ¶
type Bytes []byte
Bytes is an alias for the []byte type.
func (Bytes) Append ¶ added in v1.0.164
Append appends the given Bytes to the current Bytes.
Warning: like the builtin append, this may reuse and mutate the receiver's backing array when it has spare capacity, so the returned Bytes can alias bs. This is asymmetric with Prepend (which always copies) and with the immutable String.Append. Clone the receiver first if it must remain unchanged.
func (Bytes) Center ¶ added in v1.0.228
Center justifies the Bytes by adding padding on both sides, up to the specified length. If the length of the Bytes is already greater than or equal to the specified length, or the pad is empty, the original Bytes is returned.
The padding Bytes is repeated as necessary to evenly distribute the remaining length on both sides. The padding is added to the left and right of the Bytes.
Unlike String.Center, which counts runes, both length and padding are measured in bytes.
Parameters:
- length: The desired length of the resulting justified Bytes.
- pad: The Bytes used as padding.
Example usage:
bs := g.Bytes("Hello")
result := bs.Center(10, g.Bytes("..."))
// result: "..Hello..."
func (Bytes) Chars ¶ added in v1.0.228
Chars splits the Bytes into individual UTF-8 characters and returns the iterator. It is the canonical way to iterate runes of Bytes, equivalent to bs.Split(Bytes("")) and mirrors String.Chars.
func (Bytes) Chunks ¶ added in v1.0.228
Chunks splits the Bytes into chunks of the specified size.
This function iterates through the Bytes, yielding chunks of the specified size. If size is less than or equal to 0 or the Bytes is empty, it returns an empty SeqSlice[Bytes]. If size is greater than or equal to the length of the Bytes, it returns a SeqSlice[Bytes] containing the original Bytes.
Unlike String.Chunks, which counts runes, the chunk size is measured in bytes, so multibyte UTF-8 sequences may be split across chunks.
The yielded chunks are subslices sharing memory with the original Bytes, as with Split; clone them if independent copies are needed.
Parameters:
- size (Int): The size of the chunks to split the Bytes into.
Returns:
- SeqSlice[Bytes]: A sequence of Bytes chunks of the specified size.
Example usage:
bs := g.Bytes("Hello, World!")
chunks := bs.Chunks(4).Collect()
chunks contains {"Hell", "o, W", "orld", "!"}.
func (Bytes) Cmp ¶ added in v1.0.70
Cmp compares the Bytes with another Bytes and returns an cmp.Ordering.
func (Bytes) Compress ¶ added in v1.0.225
func (bs Bytes) Compress() bcompress
Compress returns a bcompress struct wrapping the given Bytes.
func (Bytes) ContainsAll ¶
ContainsAll checks if the Bytes contains all of the specified Bytes.
func (Bytes) ContainsAny ¶
ContainsAny checks if the Bytes contains any of the specified Bytes.
func (Bytes) ContainsAnyChars ¶
ContainsAnyChars checks if the given Bytes contains any characters from the input String.
func (Bytes) ContainsRune ¶
ContainsRune checks if the Bytes contains the specified rune.
func (Bytes) Cut ¶ added in v1.0.228
Cut returns two Bytes values. The first Bytes contains the remainder of the original Bytes after the cut. The second Bytes contains the bytes between the first occurrences of the 'start' and 'end' markers, with tags removed if specified.
The function searches for the 'start' and 'end' markers within the Bytes. If both are found, it returns the first Bytes containing the remainder of the original Bytes after the cut, followed by the second Bytes containing the bytes between the first occurrences of 'start' and 'end' with tags removed if specified.
If either 'start' or 'end' is empty or not found in the Bytes, it returns the original Bytes as the first Bytes, and an empty Bytes as the second.
Parameters:
- start (Bytes): The Bytes marking the beginning of the segment to be cut.
- end (Bytes): The Bytes marking the end of the segment to be cut.
- rmtags (bool, optional): An optional boolean parameter indicating whether to remove the matched region (including the 'start' and 'end' tags) from the remainder. Defaults to false, in which case the remainder equals the original Bytes and only the cut content is extracted.
Returns:
Bytes: The first Bytes containing the remainder of the original Bytes. When rmtags is true the matched region is removed from it; otherwise it is the original Bytes. Returns the original Bytes if 'start' or 'end' is empty or not found.
Bytes: The second Bytes containing the bytes between the first occurrences of 'start' and 'end', or an empty Bytes if 'start' or 'end' is empty or not found.
Example usage:
bs := g.Bytes("Hello, [world]! How are you?")
remainder, cut := bs.Cut(g.Bytes("["), g.Bytes("]"), true)
// remainder: "Hello, ! How are you?"
// cut: "world"
func (Bytes) Decode ¶ added in v1.0.219
func (bs Bytes) Decode() bdecode
Decode returns a bdecode struct wrapping the given Bytes.
func (Bytes) Decompress ¶ added in v1.0.225
func (bs Bytes) Decompress() bdecompress
Decompress returns a bdecompress struct wrapping the given Bytes.
func (Bytes) Encode ¶ added in v1.0.219
func (bs Bytes) Encode() bencode
Encode returns a bencode struct wrapping the given Bytes.
func (Bytes) EndsWith ¶ added in v1.0.225
EndsWith checks if the Bytes ends with the specified suffix.
func (Bytes) EndsWithAny ¶ added in v1.0.225
EndsWithAny checks if the Bytes ends with any of the provided suffixes. The method accepts a variable number of arguments, allowing for checking against multiple suffixes at once. It iterates over the provided suffixes and uses the HasSuffix function from the bytes package to check if the Bytes ends with each suffix. The function returns true if the Bytes ends with any of the suffixes, and false otherwise.
func (Bytes) Fields ¶ added in v1.0.77
Fields splits the Bytes into a slice of substrings, removing any whitespace, and returns the iterator.
func (Bytes) FieldsBy ¶ added in v1.0.77
FieldsBy splits the Bytes into a slice of substrings using a custom function to determine the field boundaries, and returns the iterator.
func (Bytes) FloatBE ¶ added in v1.0.180
FloatBE interprets the Bytes as an IEEE-754 64-bit float in BigEndian order. If the Bytes length is not exactly 8, returns 0.
func (Bytes) FloatLE ¶ added in v1.0.180
FloatLE interprets the Bytes as an IEEE-754 64-bit float in LittleEndian order. If the Bytes length is not exactly 8, returns 0.
func (Bytes) Gte ¶ added in v1.0.225
Gte checks if the Bytes is greater than or equal to another Bytes.
func (Bytes) Hash ¶
func (bs Bytes) Hash() bhash
Hash returns a bhash struct wrapping the given Bytes.
func (Bytes) Index ¶
Index returns the index of the first instance of obs in bs, or -1 if obs is not present in bs.
func (Bytes) IndexByte ¶
IndexByte returns the index of the first instance of the byte b in bs, or -1 if b is not present in bs.
func (Bytes) IndexRune ¶
IndexRune returns the index of the first instance of the rune r in bs, or -1 if r is not present in bs.
func (Bytes) IntBE ¶ added in v1.0.179
IntBE interprets the Bytes as a signed 64-bit integer in BigEndian order. If the Bytes length is less than 8, the value is sign-extended to 64 bits (the most-significant byte's high bit determines the sign). If the Bytes length is greater than 8, only the last 8 bytes are used.
func (Bytes) IntLE ¶ added in v1.0.179
IntLE interprets the Bytes as a signed 64-bit integer in LittleEndian order. If the Bytes length is less than 8, the value is sign-extended to 64 bits (the most-significant byte's high bit determines the sign). If the Bytes length is greater than 8, only the first 8 bytes are used.
func (Bytes) IsDigit ¶ added in v1.0.228
IsDigit checks if the Bytes is non-empty and all bytes are ASCII digits ('0'-'9'). Unlike String.IsDigit, which is rune-aware and accepts Unicode digits, this method operates byte-wise and only recognizes ASCII digits.
func (Bytes) IsLower ¶ added in v1.0.195
IsLower reports whether bs contains at least one letter and no uppercase letters.
func (Bytes) IsTitle ¶ added in v1.0.213
IsTitle reports whether bs is in title case: the first letter of each word is uppercase (or titlecase), the remaining letters are lowercase. Non-letter characters act as word separators. Returns false if bs has no letters.
func (Bytes) IsUpper ¶ added in v1.0.195
IsUpper reports whether bs contains at least one letter and no lowercase letters.
func (Bytes) LastIndex ¶
LastIndex returns the index of the last instance of obs in bs, or -1 if obs is not present in bs.
func (Bytes) LastIndexByte ¶
LastIndexByte returns the index of the last instance of the byte b in bs, or -1 if b is not present in bs.
func (Bytes) LeftJustify ¶ added in v1.0.228
LeftJustify justifies the Bytes to the left by adding padding to the right, up to the specified length. If the length of the Bytes is already greater than or equal to the specified length, or the pad is empty, the original Bytes is returned.
The padding Bytes is repeated as necessary to fill the remaining length. The padding is added to the right of the Bytes.
Unlike String.LeftJustify, which counts runes, both length and padding are measured in bytes.
Parameters:
- length: The desired length of the resulting justified Bytes.
- pad: The Bytes used as padding.
Example usage:
bs := g.Bytes("Hello")
result := bs.LeftJustify(10, g.Bytes("..."))
// result: "Hello....."
func (Bytes) Lte ¶ added in v1.0.225
Lte checks if the Bytes is less than or equal to another Bytes.
func (Bytes) NormalizeNFC ¶
NormalizeNFC returns a new Bytes with its Unicode characters normalized using the NFC form.
func (Bytes) Print ¶
Print writes the content of the Bytes to the standard output (console) and returns the Bytes unchanged.
func (Bytes) Println ¶ added in v1.0.122
Println writes the content of the Bytes to the standard output (console) with a newline and returns the Bytes unchanged.
func (Bytes) Regexp ¶ added in v1.0.123
func (bs Bytes) Regexp() regexpb
Regexp wraps a Bytes into an re struct to provide regex-related methods.
func (Bytes) Remove ¶ added in v1.0.228
Remove removes all occurrences of the specified patterns from the Bytes.
Both this method and String.Remove match patterns as raw byte sequences, so the two versions behave identically on the same data.
Parameters:
- patterns ...Bytes: Patterns to be removed from the Bytes. Specify as many patterns as needed.
Returns:
- Bytes: A new Bytes with all specified patterns removed. The receiver is not modified. If no patterns are given, the original Bytes is returned.
Example usage:
original := g.Bytes("Hello, world! This is a test.")
modified := original.Remove(
g.Bytes("Hello"),
g.Bytes("test"),
)
// modified contains ", world! This is a ."
func (Bytes) Repeat ¶
Repeat returns a new Bytes consisting of the current Bytes repeated 'count' times.
func (Bytes) Replace ¶
Replace replaces the first 'n' occurrences of 'oldB' with 'newB' in the Bytes.
func (Bytes) ReplaceAll ¶
ReplaceAll replaces all occurrences of 'oldB' with 'newB' in the Bytes.
func (Bytes) ReplaceMulti ¶ added in v1.0.228
ReplaceMulti performs multiple replacements within the Bytes.
The replacements are provided as pairs of old and new Bytes, in the same order as in String.ReplaceMulti. Replacements are performed in a single pass: at each position the earliest, longest match among the old patterns wins, and matches do not overlap. The number of arguments must be even; otherwise the method panics.
Both this method and String.ReplaceMulti match patterns as raw byte sequences, so the two versions behave identically on the same data.
Parameters:
- oldnew ...Bytes: Pairs of Bytes to be replaced. Specify as many pairs as needed.
Returns:
- Bytes: A new Bytes with replacements applied. The receiver is not modified.
Example usage:
original := g.Bytes("Hello, world! This is a test.")
replaced := original.ReplaceMulti(
g.Bytes("Hello"), g.Bytes("Greetings"),
g.Bytes("world"), g.Bytes("universe"),
g.Bytes("test"), g.Bytes("example"),
)
// replaced contains "Greetings, universe! This is a example."
func (Bytes) ReplaceNth ¶ added in v1.0.228
ReplaceNth returns a new Bytes with the nth occurrence of oldB replaced with newB. If there aren't enough occurrences of oldB, the original Bytes is returned. If n is less than -1, the original Bytes is also returned. If n is -1, the last occurrence of oldB is replaced with newB.
Both this method and String.ReplaceNth match patterns as raw byte sequences, so the two versions behave identically on the same data.
Returns:
- Bytes: A new Bytes with the nth occurrence of oldB replaced with newB. The receiver is not modified.
Example usage:
bs := g.Bytes("The quick brown dog jumped over the lazy dog.")
result := bs.ReplaceNth(g.Bytes("dog"), g.Bytes("fox"), 2)
fmt.Println(result)
Output: "The quick brown dog jumped over the lazy fox.".
func (*Bytes) Reset ¶ added in v1.0.148
func (bs *Bytes) Reset()
Reset resets the length of the Bytes slice to zero, preserving its capacity.
func (Bytes) Reverse ¶
Reverse reverses bytes for ASCII or invalid UTF-8 for valid UTF-8 it reverses by runes.
func (Bytes) RightJustify ¶ added in v1.0.228
RightJustify justifies the Bytes to the right by adding padding to the left, up to the specified length. If the length of the Bytes is already greater than or equal to the specified length, or the pad is empty, the original Bytes is returned.
The padding Bytes is repeated as necessary to fill the remaining length. The padding is added to the left of the Bytes.
Unlike String.RightJustify, which counts runes, both length and padding are measured in bytes.
Parameters:
- length: The desired length of the resulting justified Bytes.
- pad: The Bytes used as padding.
Example usage:
bs := g.Bytes("Hello")
result := bs.RightJustify(10, g.Bytes("..."))
// result: ".....Hello"
func (*Bytes) Scan ¶ added in v1.0.198
Scan implements the database/sql.Scanner interface for g.Bytes.
Behavior:
- If src is nil, the Bytes slice is set to nil (SQL NULL).
- If src is a []byte, a copy is stored (database/sql may reuse the driver's buffer on the next row, so the bytes must not be retained by reference).
- Otherwise, an error is returned.
Supported SQL types (common):
- BLOB / BYTEA → []byte
Notes:
- This allows g.Bytes to be used directly with database/sql and compatible drivers.
func (Bytes) Similarity ¶ added in v1.0.228
Similarity calculates the similarity between two Bytes using the Levenshtein distance algorithm and returns the similarity percentage as a Float.
The function compares two Bytes using the Levenshtein distance, which measures the difference between two sequences by counting the number of single-byte edits required to change one sequence into the other. The similarity is then calculated by normalizing the distance by the maximum length of the two input Bytes.
Unlike String.Similarity, which compares runes, this method operates byte-wise, so multibyte UTF-8 sequences are compared byte by byte.
Parameters:
- obs (Bytes): The Bytes to compare with bs.
Returns:
- Float: The similarity percentage between the two Bytes as a value between 0 and 100.
Example usage:
b1 := g.Bytes("kitten")
b2 := g.Bytes("sitting")
similarity := b1.Similarity(b2) // 57.14285714285714
func (Bytes) Split ¶
Split splits the Bytes by the specified separator and returns the iterator. If sep is empty, the Bytes are split after each UTF-8 rune; Chars is the canonical way to iterate runes.
func (Bytes) SplitAfter ¶ added in v1.0.77
SplitAfter splits the Bytes after each instance of the specified separator and returns the iterator.
func (Bytes) SplitN ¶ added in v1.0.225
SplitN splits the Bytes into substrings using the provided separator and returns an Slice[Bytes] of the results. The n parameter controls the number of substrings to return: - If n is negative, there is no limit on the number of substrings returned. - If n is zero, an empty Slice[Bytes] is returned. - If n is positive, at most n substrings are returned.
func (Bytes) StartsWith ¶ added in v1.0.225
StartsWith checks if the Bytes starts with the specified prefix.
func (Bytes) StartsWithAny ¶ added in v1.0.225
StartsWithAny checks if the Bytes starts with any of the provided prefixes. The method accepts a variable number of arguments, allowing for checking against multiple prefixes at once. It iterates over the provided prefixes and uses the HasPrefix function from the bytes package to check if the Bytes starts with each prefix. The function returns true if the Bytes starts with any of the prefixes, and false otherwise.
func (Bytes) StringUnsafe ¶ added in v1.0.147
StringUnsafe converts the Bytes into a String without copying memory. Warning: the resulting String shares the same underlying memory as the original Bytes. If the Bytes is modified later, the String will reflect those changes and may cause undefined behavior.
func (Bytes) StripPrefix ¶ added in v1.0.81
StripPrefix trims the specified Bytes prefix from the Bytes.
func (Bytes) StripSuffix ¶ added in v1.0.81
StripSuffix trims the specified Bytes suffix from the Bytes.
func (Bytes) SubBytes ¶ added in v1.0.228
SubBytes extracts a subrange from the Bytes starting at the 'start' index and ending before the 'end' index. The function also supports an optional 'step' parameter to define the increment between indices in the result. If 'start' or 'end' index is negative, they represent positions relative to the end of the Bytes: - A negative 'start' index indicates the position from the end of the Bytes, moving backward. - A negative 'end' index indicates the position from the end of the Bytes. The function ensures that indices are adjusted to fall within the valid range of the Bytes' length. Out-of-bounds indices are clamped to the Bytes' bounds instead of panicking; if 'start' exceeds 'end' (for a positive step) the result is an empty Bytes.
Unlike String.SubString, which indexes runes, all indices and the step are measured in bytes, so a boundary that falls inside a multibyte UTF-8 sequence splits the rune and the result may not be valid UTF-8. A negative step reverses bytes, not runes.
The result is a newly allocated Bytes; the receiver is not modified.
func (Bytes) Transform ¶ added in v1.0.89
Transform applies a transformation function to the Bytes and returns the result.
func (Bytes) TrimEndSet ¶ added in v1.0.82
TrimEndSet removes the specified set of characters from the end of the Bytes.
func (Bytes) TrimSet ¶ added in v1.0.82
TrimSet trims the specified set of characters from both the beginning and end of the Bytes.
func (Bytes) TrimStartSet ¶ added in v1.0.82
TrimStartSet removes the specified set of characters from the beginning of the Bytes.
func (Bytes) Truncate ¶ added in v1.0.228
Truncate shortens the Bytes to the specified maximum length. If the Bytes exceeds the specified length, it is truncated, and an ellipsis ("...") is appended to indicate the truncation.
If the length of the Bytes is less than or equal to the specified maximum length, the original Bytes is returned unchanged.
Unlike String.Truncate, which is rune-aware, this method truncates based on the number of bytes, so multibyte UTF-8 sequences may be split.
Parameters:
- max: The maximum number of bytes allowed in the resulting Bytes.
Returns:
- A new Bytes truncated to the specified maximum length with "..." appended if truncation occurs. Otherwise, returns the original Bytes.
Example usage:
bs := g.Bytes("Hello, World!")
result := bs.Truncate(5)
// result: "Hello..."
bs2 := g.Bytes("Short")
result2 := bs2.Truncate(10)
// result2: "Short"
func (Bytes) TryBigInt ¶ added in v1.0.228
TryBigInt parses the Bytes as a *big.Int, mirroring String.TryBigInt.
func (Bytes) TryBool ¶ added in v1.0.228
TryBool parses the Bytes as a bool, mirroring String.TryBool.
func (Bytes) TryComplex ¶ added in v1.0.228
func (bs Bytes) TryComplex() Result[complex128]
TryComplex parses the Bytes as a complex number, mirroring String.TryComplex.
func (Bytes) TryFloat ¶ added in v1.0.228
TryFloat parses the Bytes as a float, mirroring String.TryFloat.
func (Bytes) TryInt ¶ added in v1.0.228
TryInt parses the Bytes as an integer, mirroring String.TryInt.
type Deque ¶ added in v1.0.181
type Deque[T any] struct { // contains filtered or unexported fields }
Deque is a double-ended queue implemented with a growable ring buffer. It provides efficient insertion and removal of elements at both ends.
func DequeFromSlice ¶ added in v1.0.228
DequeFromSlice builds a Deque from a slice. Unlike the variadic DequeOf, it takes the slice directly, so it can be passed as a first-class function — e.g. as the collect step after a chain: res.TryCollect().Map(DequeFromSlice).
func NewDeque ¶ added in v1.0.181
NewDeque creates a new Deque of the given generic type T with the specified capacity. The capacity parameter specifies the initial capacity of the underlying slice. If no capacity is provided, an empty Deque with a capacity of 0 is returned.
Parameters:
- capacity ...Int: An optional parameter specifying the initial capacity of the Deque
Returns:
- Deque[T]: A new Deque of the specified generic type T with the given capacity
Example usage:
d1 := g.NewDeque[int]() // Creates an empty Deque of type int d2 := g.NewDeque[int](10) // Creates an empty Deque with capacity of 10
func (*Deque[T]) Back ¶ added in v1.0.181
Back returns a reference to the last element. Returns None if the Deque is empty.
func (*Deque[T]) BinarySearch ¶ added in v1.0.181
BinarySearch searches for a value in a sorted Deque using binary search. Returns the index where the value is found, or where it should be inserted.
func (*Deque[T]) Clear ¶ added in v1.0.181
func (dq *Deque[T]) Clear()
Clear removes all elements from the Deque.
func (*Deque[T]) Contains ¶ added in v1.0.181
Contains checks if the Deque contains the specified value.
func (*Deque[T]) ContainsAll ¶ added in v1.0.225
ContainsAll checks if the Deque contains all of the provided values.
func (*Deque[T]) ContainsAny ¶ added in v1.0.225
ContainsAny checks if the Deque contains any element from the provided values.
func (*Deque[T]) Extend ¶ added in v1.0.228
func (dq *Deque[T]) Extend(values ...T)
Extend appends the given values to the back of the Deque, in order. It accepts a spread slice too: dq.Extend(sl...).
func (*Deque[T]) Front ¶ added in v1.0.181
Front returns a reference to the first element. Returns None if the Deque is empty.
func (*Deque[T]) Get ¶ added in v1.0.181
Get retrieves an element at the specified index. Index 0 represents the front of the Deque. Returns None if the index is out of bounds.
func (*Deque[T]) Index ¶ added in v1.0.181
Index returns the index of the first occurrence of the specified value, or -1 if not found.
func (*Deque[T]) Insert ¶ added in v1.0.181
Insert inserts an element at the specified index. Index 0 represents the front of the Deque. Panics if the index is out of bounds (index < 0 or index > Len()).
func (*Deque[T]) IsEmpty ¶ added in v1.0.181
IsEmpty returns true if the Deque contains no elements.
func (*Deque[T]) Iter ¶ added in v1.0.181
Iter returns an iterator for the Deque, allowing for sequential iteration over its elements from front to back.
func (*Deque[T]) IterReverse ¶ added in v1.0.181
IterReverse returns an iterator for the Deque that allows for sequential iteration over its elements in reverse order (from back to front).
func (*Deque[T]) MakeContiguous ¶ added in v1.0.181
MakeContiguous rearranges the internal storage of the Deque so that its elements are in contiguous memory. Returns a slice that contains all elements.
func (*Deque[T]) PopBack ¶ added in v1.0.181
PopBack removes and returns the last element of the Deque. Returns None if the Deque is empty.
func (*Deque[T]) PopFront ¶ added in v1.0.181
PopFront removes and returns the first element of the Deque. Returns None if the Deque is empty.
func (*Deque[T]) Print ¶ added in v1.0.181
Print writes the elements of the Deque to the standard output (console) and returns the Deque unchanged.
func (*Deque[T]) Println ¶ added in v1.0.181
Println writes the elements of the Deque to the standard output (console) with a newline and returns the Deque unchanged.
func (*Deque[T]) PushBack ¶ added in v1.0.181
func (dq *Deque[T]) PushBack(value T)
PushBack adds an element to the back of the Deque.
func (*Deque[T]) PushFront ¶ added in v1.0.181
func (dq *Deque[T]) PushFront(value T)
PushFront adds an element to the front of the Deque.
func (*Deque[T]) Remove ¶ added in v1.0.181
Remove removes and returns the element at the specified index. Returns None if the index is out of bounds.
func (*Deque[T]) Reserve ¶ added in v1.0.181
Reserve ensures that the Deque can hold at least the specified number of elements without reallocating. If the current capacity is already sufficient, this is a no-op.
func (*Deque[T]) Retain ¶ added in v1.0.181
Retain keeps only the elements specified by the predicate.
func (*Deque[T]) RotateLeft ¶ added in v1.0.181
RotateLeft rotates the Deque in-place such that the first mid elements move to the end while the last len - mid elements move to the front.
func (*Deque[T]) RotateRight ¶ added in v1.0.181
RotateRight rotates the Deque in-place such that the first len - k elements move to the end while the last k elements move to the front.
func (*Deque[T]) Set ¶ added in v1.0.181
Set sets the element at the specified index, returning the old value as an Option. Index 0 represents the front of the Deque. Returns None if the index is out of bounds.
func (*Deque[T]) ShrinkToFit ¶ added in v1.0.181
func (dq *Deque[T]) ShrinkToFit()
ShrinkToFit shrinks the capacity of the Deque as much as possible.
func (*Deque[T]) Slice ¶ added in v1.0.205
Slice converts the Deque to a Slice, maintaining element order.
type Dir ¶
type Dir struct {
// contains filtered or unexported fields
}
Dir is a struct representing a directory path.
func TempDir ¶ added in v1.0.228
func TempDir() *Dir
TempDir returns the default directory to use for temporary files.
On Unix systems, it returns $TMPDIR if non-empty, else /tmp. On Windows, it uses GetTempPath, returning the first non-empty value from %TMP%, %TEMP%, %USERPROFILE%, or the Windows directory. On Plan 9, it returns /tmp.
The directory is neither guaranteed to exist nor have accessible permissions.
func (*Dir) Chown ¶
Chown changes the ownership of the directory to the specified UID and GID. It uses os.Chown to modify ownership and returns a Result[*Dir] indicating success or failure.
func (*Dir) Copy ¶
Copy copies the contents of the current directory to the destination directory.
Parameters:
- dest (String): The destination directory where the contents of the current directory should be copied.
- followLinks (optional): A boolean indicating whether to follow symbolic links during the walk. If true, symbolic links are followed; otherwise, they are skipped.
Returns:
- Result[*Dir]: A Result type containing either a pointer to a new Dir instance representing the destination directory or an error.
Example usage:
sourceDir := g.NewDir("path/to/source")
destinationDirResult := sourceDir.Copy("path/to/destination")
if destinationDirResult.IsErr() {
// Handle error
}
destinationDir := destinationDirResult.Ok()
func (*Dir) Create ¶
Create creates a new directory with the specified mode (optional).
Parameters:
- mode (os.FileMode, optional): The file mode for the new directory. If not provided, it defaults to DirDefault (0755).
Returns:
- *Dir: A pointer to the Dir instance on which the method was called.
Example usage:
dir := g.NewDir("path/to/directory")
createdDir := dir.Create(0755) // Optional mode argument
func (*Dir) CreateAll ¶
CreateAll creates all directories along the given path, with the specified mode (optional).
Parameters:
- mode ...os.FileMode (optional): The file mode to be used when creating the directories. If not provided, it defaults to the value of DirDefault constant (0755).
Returns:
- *Dir: A pointer to the Dir instance representing the created directories.
Example usage:
dir := g.NewDir("path/to/directory")
dir.CreateAll()
dir.CreateAll(0755)
func (*Dir) Exists ¶ added in v1.0.228
Exists checks if the current directory exists.
Returns:
- bool: true if the current directory exists, false otherwise.
Example usage:
dir := g.NewDir("path/to/directory")
exists := dir.Exists()
func (*Dir) Glob ¶
Glob iterates over files in the current directory matching a specified pattern and yields File instances for each match. This method utilizes a lazy evaluation strategy, processing files as they are needed.
Returns:
- SeqResult[*File]: A sequence of Result[*File] instances representing the files that match the provided pattern in the current directory. It returns an error if the glob operation fails.
Example usage:
dir := g.NewDir("path/to/directory/*.txt")
files := dir.Glob()
for file := range files {
fmt.Println(file.Ok().Name())
}
func (*Dir) Join ¶
Join joins the current directory path with the given path elements, returning the joined path.
Parameters:
- elem (...String): One or more String values representing path elements to be joined with the current directory path.
Returns:
- String: The resulting joined path as an String.
Example usage:
dir := g.NewDir("path/to/directory")
joinedPath := dir.Join("subdir", "file.txt")
func (*Dir) Lstat ¶
Lstat retrieves information about the symbolic link represented by the Dir instance. It returns a Result[fs.FileInfo] containing details about the symbolic link's metadata. Unlike Stat, Lstat does not follow the link and provides information about the link itself.
func (*Dir) Move ¶
Move function simply calls Dir.Rename
func (*Dir) Path ¶
Path returns the absolute path of the current directory.
Returns:
- String: The absolute path of the current directory as an String. If an error occurs while converting the path to an absolute path, the error is stored in d.err, which can be checked using the Error() method.
Example usage:
dir := g.NewDir("path/to/directory")
absPath := dir.Path()
func (*Dir) Print ¶
Print writes the content of the Dir to the standard output (console) and returns the Dir unchanged.
func (*Dir) Println ¶ added in v1.0.122
Println writes the content of the Dir to the standard output (console) with a newline and returns the Dir unchanged.
func (*Dir) Read ¶
Read lazily iterates over the content of the current directory and yields a File for each entry. Entries are read in bounded batches and retain the filesystem order; callers that need sorted output can collect and sort them.
Returns:
- SeqResult[*File]: A sequence of Result[*File] instances representing each file and directory in the current directory. It returns an error if reading the directory fails.
Example usage:
dir := g.NewDir("path/to/directory")
files := dir.Read()
for file := range files {
fmt.Println(file.Ok().Name())
}
func (*Dir) Remove ¶
Remove attempts to delete the directory and its contents. It returns a Result, which contains either the *Dir or an error. If the directory does not exist, Remove returns a successful Result with *Dir set. Any error that occurs during removal will be of type *PathError.
func (*Dir) Rename ¶
Rename renames the current directory to the new path.
Parameters:
- newpath String: The new path for the directory.
Returns:
- *Dir: A pointer to the Dir instance representing the renamed directory. If an error occurs, the original Dir instance is returned with the error stored in d.err, which can be checked using the Error() method.
Example usage:
dir := g.NewDir("path/to/directory")
dir.Rename("path/to/new_directory")
func (*Dir) SetPath ¶
SetPath sets the path of the current directory.
Parameters:
- path (String): The new path to be set for the current directory.
Returns:
- *Dir: A pointer to the updated Dir instance with the new path.
Example usage:
dir := g.NewDir("path/to/directory")
dir.SetPath("new/path/to/directory")
func (*Dir) Stat ¶
Stat retrieves information about the directory represented by the Dir instance. It returns a Result[fs.FileInfo] containing details about the directory's metadata.
func (*Dir) String ¶ added in v1.0.86
String returns the String representation of the current directory's path.
func (*Dir) Walk ¶
Walk returns a lazy sequence of all files and directories under the current Dir. You can customize inclusion/exclusion using SeqResult methods (Exclude, Filter, etc.).
Example usage:
NewDir("path/to/dir").
Walk().
Exclude((*File).IsLink).
ForEach(func(r Result[*File]) {
if r.IsOk() {
fmt.Println(r.Ok().Path().Ok().Std())
}
})
type Entry ¶ added in v1.0.200
type Entry[K comparable, V any] interface { Key() K OrInsert(value V) V OrInsertWith(fn func() V) V OrInsertWithKey(fn func(K) V) V OrDefault() V AndModify(fn func(*V)) Entry[K, V] // contains filtered or unexported methods }
Entry is a sealed interface representing a view into a single Map entry.
Entry provides an API for in-place manipulation of map entries, enabling efficient "get or insert" patterns without redundant lookups.
The interface is sealed to ensure type safety; implementations are limited to OccupiedEntry (when the key exists) and VacantEntry (when the key is absent). Use a type switch to access type-specific methods like Get, Insert, or Remove.
Common usage patterns:
// Increment existing value or insert default
m.Entry("counter").AndModify(func(v *int) { *v++ }).OrInsert(1)
// Insert only if absent
m.Entry("key").OrInsert(defaultValue)
// Insert with lazy initialization
m.Entry("key").OrInsertWith(func() V { return expensiveComputation() })
// Type switch for fine-grained control
switch e := m.Entry("key").(type) {
case OccupiedEntry[string, int]:
fmt.Println("exists:", e.Get())
case VacantEntry[string, int]:
e.Insert(42)
}
An Entry is a short-lived view of the key state observed by Map.Entry. Do not retain it across external insertion or removal of the same key; obtain a fresh Entry after structurally changing that key.
type ErrFileClosed ¶
type ErrFileClosed struct{ Msg string }
ErrFileClosed represents an error for when a file is already closed.
func (*ErrFileClosed) Error ¶
func (e *ErrFileClosed) Error() string
Error returns the error message for ErrFileClosed.
type ErrFileNotExist ¶
type ErrFileNotExist struct{ Msg string }
ErrFileNotExist represents an error for when a file does not exist.
func (*ErrFileNotExist) Error ¶
func (e *ErrFileNotExist) Error() string
Error returns the error message for ErrFileNotExist.
type File ¶
type File struct {
// contains filtered or unexported fields
}
File is a struct that represents a file along with an iterator for reading lines.
func (*File) Append ¶
Append appends the given content to the file, with the specified mode (optional). If no FileMode is provided, the default FileMode (0644) is used. Don't forget to close the file!
func (*File) Chunks ¶ added in v1.0.57
Chunks returns a new iterator instance that can be used to read the file in fixed-size chunks of the specified size in bytes.
Parameters:
- size (int): The size of each chunk in bytes.
Example usage:
// Open a new file with the specified name "text.txt"
g.NewFile("text.txt").
Chunks(100). // Read the file in chunks of 100 bytes
Map(g.String.Upper). // Convert each chunk to uppercase
ForEach( // For each line, print it
func(func(s Result[String]) {
s.Ok().Print()
})
// Output:
// UPPERCASED_CHUNK1
// UPPERCASED_CHUNK2
// UPPERCASED_CHUNK3
func (*File) ChunksRaw ¶ added in v1.0.150
ChunksRaw returns a new iterator instance that reads the file in fixed-size chunks of bytes, yielding each chunk as a Bytes slice.
This method avoids intermediate string allocations and operates directly on byte slices. Each chunk is copied from the underlying buffer to make it safe for downstream use.
Parameters:
- size (Int): The size of each chunk in bytes. Must be > 0.
Returns:
- SeqResult[Bytes]: An iterator over raw byte chunks from the file.
Example usage:
g.NewFile("text.txt").
ChunksRaw(128). // Read raw 128-byte chunks
ForEach(func(chunk g.Result[g.Bytes]) {
chunk.Ok().Print()
})
Output: RAW_CHUNK_1 RAW_CHUNK_2 ...
Note: Each chunk is copied from the buffer to ensure memory safety.
func (*File) Close ¶
Close closes the File and unlocks its underlying file, if it is not already closed.
func (*File) Copy ¶
Copy copies the file to the specified destination, with the specified mode (optional). If no mode is provided, the default FileMode (0644) is used.
func (*File) Create ¶
Create is similar to os.Create, but it returns a write-locked file. Don't forget to close the file!
func (*File) CreateTemp ¶
CreateTemp creates a new temporary file in the specified directory with the specified name pattern and returns a Result, which contains a pointer to the File or an error if the operation fails. If no directory is specified, the default directory for temporary files is used. If no name pattern is specified, the default pattern "*" is used.
Parameters:
- args ...String: A variadic parameter specifying the directory and/or name pattern for the temporary file.
Returns:
- *File: A pointer to the File representing the temporary file.
Example usage:
f := g.NewFile("")
tmpfile := f.CreateTemp() // Creates a temporary file with default settings
tmpfileWithDir := f.CreateTemp("mydir") // Creates a temporary file in "mydir" directory
tmpfileWithPattern := f.CreateTemp("", "tmp") // Creates a temporary file with "tmp" pattern
func (*File) Decode ¶ added in v1.0.85
func (f *File) Decode() fdecode
Decode returns an fdecode struct wrapping the given file for decoding.
func (*File) Encode ¶ added in v1.0.85
func (f *File) Encode() fencode
Encode returns an fencode struct wrapping the given file for encoding.
func (*File) Guard ¶
Guard sets a lock on the file to protect it from concurrent access. It returns the File instance with the guard enabled.
func (*File) Lines ¶
Lines returns a new iterator instance that can be used to read the file line by line.
Example usage:
// Open a new file with the specified name "text.txt"
g.NewFile("text.txt").
Lines(). // Read the file line by line
Skip(3). // Skip the first 3 lines
Exclude(f.Zero). // Exclude lines that are empty or contain only whitespaces
Dedup(). // Remove consecutive duplicate lines
Map(g.String.Upper). // Convert each line to uppercase
ForEach( // For each line, print it
func(func(s Result[String]) {
s.Ok().Print()
})
// Output:
// UPPERCASED_LINE4
// UPPERCASED_LINE5
// UPPERCASED_LINE6
func (*File) LinesRaw ¶ added in v1.0.150
LinesRaw returns a new iterator instance that reads the file line by line, yielding each line as a Bytes slice (raw []byte).
This version avoids intermediate string allocations by working directly with byte slices. The returned Bytes are copies of the scanner buffer and are safe to retain.
Returns:
- SeqResult[Bytes]: An iterator over raw byte lines from the file.
Example usage:
g.NewFile("text.txt").
LinesRaw(). // Read raw byte lines
Filter(func(b g.Bytes) bool {
return len(b) > 0
}).
ForEach(func(line g.Result[g.Bytes]) {
line.Ok().Print()
})
Output: LINE_1 LINE_2 ...
Note: Each line is copied before yielding to avoid scanner buffer reuse issues.
func (*File) Lstat ¶
Lstat retrieves information about the symbolic link represented by the *File instance. It returns a Result[fs.FileInfo] containing details about the symbolic link's metadata. Unlike Stat, Lstat does not follow the link and provides information about the link itself.
func (*File) Move ¶
Move function simply calls File.Rename
func (*File) Open ¶
Open is like os.Open, but returns a read-locked file. Don't forget to close the file!
func (*File) OpenFile ¶
OpenFile is like os.OpenFile, but returns a locked file. If flag includes os.O_WRONLY or os.O_RDWR, the file is write-locked otherwise, it is read-locked. Don't forget to close the file!
func (*File) Print ¶
Print writes the content of the File to the standard output (console) and returns the File unchanged.
func (*File) Println ¶ added in v1.0.122
Println writes the content of the File to the standard output (console) with a newline and returns the File unchanged.
func (*File) Reader ¶ added in v1.0.212
func (f *File) Reader() Result[io.ReadCloser]
Reader returns an io.ReadCloser for reading the file's contents. If the file is not already open, it attempts to open it automatically. The caller is responsible for closing the returned reader to release system resources.
func (*File) Seek ¶
Seek sets the file offset for the next Read or Write operation. The offset is specified by the 'offset' parameter, and the 'whence' parameter determines the reference point for the offset.
The 'offset' parameter specifies the new offset in bytes relative to the reference point determined by 'whence'. If 'whence' is set to io.SeekStart, io.SeekCurrent, or io.SeekEnd, the offset is relative to the start of the file, the current offset, or the end of the file, respectively.
If the file is not open, this method will attempt to open it. If the open operation fails, an error is returned.
If the Seek operation fails, the file is closed, and an error is returned.
Example:
file := g.NewFile("example.txt")
result := file.Seek(100, io.SeekStart)
if result.Err() != nil {
log.Fatal(result.Err())
}
Parameters:
- offset: The new offset in bytes.
- whence: The reference point for the offset (io.SeekStart, io.SeekCurrent, or io.SeekEnd).
Don't forget to close the file!
func (*File) Stat ¶
Stat returns the fs.FileInfo of the file. It calls the file's Stat method if the file is open, or os.Stat otherwise.
func (*File) Std ¶
Std returns the underlying *os.File instance. Don't forget to close the file with g.File().Close()!
type Float ¶
type Float float64
Float is an alias for the float64 type.
func NewFloat ¶
func NewFloat[T constraints.Float | constraints.Integer](float T) Float
NewFloat creates a new Float with the provided value.
func (Float) Atan2 ¶ added in v1.0.228
Atan2 returns the arctangent of f/b (with f as y and b as x), in radians, using the signs of the two to determine the quadrant of the result.
func (Float) BytesBE ¶ added in v1.0.180
BytesBE returns the IEEE-754 representation of the Float as Bytes in BigEndian order. The Float is converted to its 64-bit IEEE-754 binary representation.
func (Float) BytesLE ¶ added in v1.0.180
BytesLE returns the IEEE-754 representation of the Float as Bytes in LittleEndian order. The Float is converted to its 64-bit IEEE-754 binary representation.
func (Float) Ceil ¶ added in v1.0.228
Ceil returns the least integer value greater than or equal to the Float.
func (Float) CeilDecimal ¶ added in v1.0.194
CeilDecimal rounds the Float value up (towards +Inf) to the specified number of decimal places.
Parameters:
- precision (Int): The number of decimal places to round up to. If negative, the Float is returned unchanged. Values greater than 308 are capped at 308.
Returns:
- Float: A new Float value rounded up to the specified number of decimal places. If scaling by 10^precision overflows to a non-finite value (±Inf/NaN), the Float is returned unchanged.
func (Float) Clamp ¶ added in v1.0.228
Clamp restricts the Float to the inclusive range [min, max]. If the Float is NaN, NaN is returned. The caller must ensure min <= max and that neither bound is NaN: this method does not panic on an invalid range — a NaN bound never compares true, so the corresponding check is silently skipped, and with min > max the lower bound wins.
func (Float) Cmp ¶ added in v1.0.70
Cmp compares two Floats and returns an cmp.Ordering.
NaN handling is NOT IEEE 754. Comparison routes through cmp.Compare, which imposes a total order: a NaN is treated as less than every non-NaN value, and two NaNs compare as equal. Consequently Eq, Ne, Lt, Gt, Lte, and Gte all inherit this non-IEEE behavior — for example NaN.Eq(NaN) reports true and a NaN sorts as the smallest value. Use math.IsNaN(f.Std()) when strict IEEE 754 semantics (where every NaN comparison is false) are required.
func (Float) Copysign ¶ added in v1.0.228
Copysign returns a Float with the magnitude of the Float and the sign of sign.
func (Float) ExpM1 ¶ added in v1.0.228
ExpM1 returns e**f - 1, which is more accurate than Exp().Sub(1) when the Float is near zero.
func (Float) Floor ¶ added in v1.0.228
Floor returns the greatest integer value less than or equal to the Float.
func (Float) FloorDecimal ¶ added in v1.0.194
FloorDecimal rounds the Float value down (towards -Inf) to the specified number of decimal places.
Parameters:
- precision (Int): The number of decimal places to round down to. If negative, the Float is returned unchanged. Values greater than 308 are capped at 308.
Returns:
- Float: A new Float value rounded down to the specified number of decimal places. If scaling by 10^precision overflows to a non-finite value (±Inf/NaN), the Float is returned unchanged.
func (Float) Fract ¶ added in v1.0.228
Fract returns the fractional part of the Float (f - f.Trunc()). For NaN and ±Inf the result is NaN.
func (Float) Gte ¶ added in v1.0.208
Gte checks if the Float is greater than or equal to the specified Float.
func (Float) Hypot ¶ added in v1.0.228
Hypot returns Sqrt(f*f + b*b), avoiding unnecessary overflow and underflow.
func (Float) IsFinite ¶ added in v1.0.228
IsFinite reports whether the Float is neither NaN nor an infinity.
func (Float) IsInf ¶ added in v1.0.228
IsInf reports whether the Float is an infinity, either positive or negative.
func (Float) IsNaN ¶ added in v1.0.228
IsNaN reports whether the Float is an IEEE 754 "not-a-number" value.
func (Float) IsNormal ¶ added in v1.0.228
IsNormal reports whether the Float is a normal IEEE 754 number: neither zero, subnormal, infinite, nor NaN.
func (Float) IsSignNegative ¶ added in v1.0.228
IsSignNegative reports whether the Float has a negative sign bit. This includes -0.0 and negative infinity. Note: NaN carries a sign bit too, so a NaN with a set sign bit (e.g. math.Copysign(math.NaN(), -1)) is reported as sign-negative; use IsNaN to detect NaN itself.
func (Float) IsSignPositive ¶ added in v1.0.228
IsSignPositive reports whether the Float has a positive sign bit. This includes +0.0 and positive infinity. Note: NaN carries a sign bit too, so a NaN with a clear sign bit (e.g. math.NaN()) is reported as sign-positive; use IsNaN to detect NaN itself.
func (Float) Ln1p ¶ added in v1.0.228
Ln1p returns the natural logarithm of 1 plus the Float, which is more accurate than Add(1).Ln() when the Float is near zero.
func (Float) Lte ¶ added in v1.0.208
Lte checks if the Float is less than or equal to the specified Float.
func (Float) Mod ¶ added in v1.0.194
Mod returns the floating-point remainder of f / b as defined by IEEE 754.
Parameters:
- b (Float): The divisor.
Returns:
- Float: The remainder of f / b.
Example usage:
f := g.NewFloat(5.5) result := f.Mod(2) // result = 1.5
func (Float) MulAdd ¶ added in v1.0.228
MulAdd returns f*b + c computed as a fused multiply-add with only one rounding.
func (Float) Pow ¶ added in v1.0.194
Pow raises the Float to the power of the given exponent.
Parameters:
- exp (Float): The exponent to raise the Float to.
Returns:
- Float: The result of raising the Float to the specified power.
Example usage:
f := g.NewFloat(2) result := f.Pow(3) // result = 8
func (Float) Print ¶
Print writes the value of the Float to the standard output (console) and returns the Float unchanged.
func (Float) Println ¶ added in v1.0.122
Println writes the value of the Float to the standard output (console) with a newline and returns the Float unchanged.
func (Float) Recip ¶ added in v1.0.228
Recip returns the reciprocal (multiplicative inverse) of the Float, 1/f.
func (Float) Round ¶
Round rounds the Float to the nearest integer and returns the result as an Int.
func (Float) RoundDecimal ¶
RoundDecimal rounds the Float value to the specified number of decimal places.
Parameters:
- precision (Int): The number of decimal places to round to. If negative, the Float is returned unchanged. Values greater than 308 are capped at 308 to prevent overflow.
Returns:
- Float: A new Float value rounded to the specified number of decimal places. If scaling by 10^precision overflows to a non-finite value (±Inf/NaN), the Float is returned unchanged.
func (*Float) Scan ¶ added in v1.0.198
Scan implements the database/sql.Scanner interface for g.Float.
Behavior:
- If src is nil, the value is set to 0 (SQL NULL).
- If src is a float64 (common SQL REAL/DOUBLE type), it is assigned.
- Otherwise, an error is returned.
Supported SQL types (common):
- REAL / DOUBLE → float64
Notes:
- This allows g.Float to be used directly with database/sql and compatible drivers.
func (Float) Signum ¶ added in v1.0.228
Signum returns a Float representing the sign of the Float: 1 if the sign bit is clear (including +0), -1 if the sign bit is set (including -0), and NaN if the Float is NaN.
func (Float) Sqrt ¶ added in v1.0.194
Sqrt returns the square root of the Float.
Returns:
- Float: The square root of the Float. If the Float is negative, the result is NaN.
Example usage:
f := g.NewFloat(9) result := f.Sqrt() // result = 3
func (Float) Transform ¶ added in v1.0.89
Transform applies a transformation function to the Float and returns the result.
func (Float) Trunc ¶ added in v1.0.228
Trunc returns the integer part of the Float, rounding toward zero.
func (Float) TruncDecimal ¶ added in v1.0.194
TruncDecimal truncates the Float value to the specified number of decimal places.
Parameters:
- precision (Int): The number of decimal places to truncate to. If negative, the Float is returned unchanged. Values greater than 308 are capped at 308.
Returns:
- Float: A new Float value truncated to the specified number of decimal places. If scaling by 10^precision overflows to a non-finite value (±Inf/NaN), the Float is returned unchanged.
type Formattable ¶ added in v1.0.228
Formattable lets a type handle g.Format specifications without reflection. The spec is the text after ':' without the colon; an empty spec requests the type's default representation.
type Heap ¶ added in v1.0.181
type Heap[T any] struct { // contains filtered or unexported fields }
Heap is a generic binary heap data structure that maintains elements in heap order. It can be configured as either a min-heap or max-heap based on the comparison function.
func HeapFromSlice ¶ added in v1.0.228
HeapFromSlice builds a Heap from a slice using compareFn. Unlike the variadic HeapOf, it takes the slice directly; because it also needs compareFn it must be curried to serve as a collector, e.g. res.TryCollect().Map(func(s Slice[T]) *Heap[T] { return HeapFromSlice(cmp.Cmp, s) }).
func HeapOf ¶ added in v1.0.228
HeapOf creates a new Heap with the given comparison function containing the provided elements.
func NewHeap ¶ added in v1.0.181
NewHeap creates a new heap with the given comparison function. The comparison function should return: - cmp.Less if the first argument should have higher priority - cmp.Greater if the second argument should have higher priority - cmp.Equal if they have equal priority
NewHeap panics if compareFn is nil, mirroring Slice.Heap, since a nil comparison function would otherwise nil-deref on the first Push.
func (*Heap[T]) Clear ¶ added in v1.0.181
func (h *Heap[T]) Clear()
Clear removes all elements from the heap and releases the backing array, allowing the previously held elements to be garbage collected.
func (*Heap[T]) Contains ¶ added in v1.0.225
Contains reports whether the heap contains the given value.
Equality is determined the same way as Slice.Contains: a direct == fast path for comparable element types, falling back to reflect.DeepEqual for interface-typed or otherwise uncomparable values.
func (*Heap[T]) Eq ¶ added in v1.0.228
Eq checks if two Heaps are equal.
Heaps are considered equal if they yield the same elements in the same iteration order (the sorted order produced by Iter), regardless of the internal layout of their backing storage. The comparison functions themselves are not compared; each heap is drained using its own ordering.
func (*Heap[T]) Fix ¶ added in v1.0.225
Fix re-establishes the heap ordering after the element at index i has changed its value. It is equivalent to, but less expensive than, removing the element at index i and pushing the new value.
Indices follow the internal heap layout (index 0 is the root). Fix is a no-op if i is out of range. The cost is O(log n).
func (*Heap[T]) IntoIter ¶ added in v1.0.181
IntoIter returns a consuming iterator that yields elements in sorted order.
This iterator consumes the original heap by repeatedly calling Pop() until the heap is empty. After iteration completes (or is stopped early), the original heap will be empty. Elements are yielded in the order determined by the heap's comparison function (smallest first for min-heap, largest first for max-heap).
Use this method when you want to consume the heap and don't need the original data structure afterwards, or when you want to transfer ownership of the elements.
Time complexity: O(n log n) for full iteration Space complexity: O(1) - no additional memory allocation
Returns:
- SeqHeap[T]: An iterator that yields elements in sorted order while consuming the heap
Example usage:
heap := g.NewHeap(cmp.Cmp[int])
heap.Push(10, 5, 15, 1, 8)
// Consume the heap while iterating
// (Collect requires a comparison function to build the new heap)
result := heap.IntoIter().Collect(cmp.Cmp[int]) // [1, 5, 8, 10, 15]
fmt.Printf("Heap now has %d elements\n", heap.Len()) // Output: 0
// Can be stopped early, leaving remaining elements in heap
heap2 := g.NewHeap(cmp.Cmp[int])
heap2.Push(20, 25, 15, 30)
heap2.IntoIter().Take(2).ForEach(func(x int) {
fmt.Printf("%d ", x) // Output: 15 20
})
fmt.Printf("Remaining: %d elements\n", heap2.Len()) // Output: 2
func (*Heap[T]) Iter ¶ added in v1.0.181
Iter returns a non-consuming iterator that yields elements in sorted order.
The iterator creates a clone of the heap and yields elements by repeatedly calling Pop() on the clone, ensuring the original heap remains unchanged. Elements are yielded in the order determined by the heap's comparison function (smallest first for min-heap, largest first for max-heap).
Time complexity: O(n log n) for full iteration Space complexity: O(n) for the heap clone
Returns:
- SeqHeap[T]: An iterator that yields elements in sorted order
Example usage:
heap := g.NewHeap(cmp.Cmp[int])
heap.Push(10, 5, 15, 1, 8)
// Iterate without consuming the original heap
heap.Iter().ForEach(func(x int) {
fmt.Printf("%d ", x) // Output: 1 5 8 10 15
})
fmt.Printf("Heap still has %d elements\n", heap.Len()) // Output: 5
// Can be used with other iterator methods
// (Collect requires a comparison function to build the new heap)
firstThree := heap.Iter().Take(3).Collect(cmp.Cmp[int]) // [1, 5, 8]
evenNumbers := heap.Iter().Filter(func(x int) bool {
return x%2 == 0
}).Collect(cmp.Cmp[int]) // [8, 10]
func (*Heap[T]) Peek ¶ added in v1.0.181
Peek returns the top element without removing it. Returns None if the heap is empty.
func (*Heap[T]) Pop ¶ added in v1.0.181
Pop removes and returns the top element from the heap. Returns None if the heap is empty.
func (*Heap[T]) Print ¶ added in v1.0.181
Print writes the elements of the Heap to the standard output (console) and returns the Heap unchanged.
func (*Heap[T]) Println ¶ added in v1.0.181
Println writes the elements of the Heap to the standard output (console) with a newline and returns the Heap unchanged.
func (*Heap[T]) Push ¶ added in v1.0.181
func (h *Heap[T]) Push(items ...T)
Push adds one or more items to the heap.
func (*Heap[T]) Remove ¶ added in v1.0.225
Remove removes and returns the element at index i in the heap's backing storage. Indices follow the internal heap layout (index 0 is the root); use Iter or Slice to observe element positions.
Returns None if i is out of range. After removal the heap property is restored in O(log n).
func (*Heap[T]) Slice ¶ added in v1.0.205
Slice returns a slice containing all elements in the heap. The order is not guaranteed to be sorted.
type Int ¶
type Int int
Int is an alias for the int type.
func NewInt ¶
func NewInt[T constraints.Integer | rune | byte](i T) Int
NewInt creates a new Int with the provided int value.
func (Int) Abs ¶
Abs returns the absolute value of the Int. Like Go's native arithmetic it wraps on overflow: Abs of math.MinInt is math.MinInt. Use CheckedAbs for a guarded variant.
func (Int) Add ¶
Add adds two Ints and returns the result. Like Go's native arithmetic it wraps on overflow (two's complement). Use CheckedAdd, SaturatingAdd or OverflowingAdd for guarded variants.
func (Int) BytesBE ¶ added in v1.0.180
BytesBE converts the Int to Bytes in BigEndian order. Leading zero bytes are removed while preserving the sign bit for negative numbers.
func (Int) BytesLE ¶ added in v1.0.180
BytesLE converts the Int to Bytes in LittleEndian order. Trailing zero bytes are removed while preserving the sign bit for negative numbers
func (Int) CheckedAbs ¶ added in v1.0.228
CheckedAbs returns the absolute value of the Int, returning None if it overflows (i == MinInt).
func (Int) CheckedAdd ¶ added in v1.0.228
CheckedAdd adds two Ints, returning None if the addition overflows.
func (Int) CheckedDiv ¶ added in v1.0.228
CheckedDiv divides the Int by b, returning None if b is zero or the division overflows.
func (Int) CheckedMul ¶ added in v1.0.228
CheckedMul multiplies two Ints, returning None if the multiplication overflows.
func (Int) CheckedNeg ¶ added in v1.0.228
CheckedNeg negates the Int, returning None if the negation overflows (i == MinInt).
func (Int) CheckedPow ¶ added in v1.0.228
CheckedPow raises the Int to the power of exp using exponentiation by squaring, returning None if exp is negative or the computation overflows. An exp of zero yields Some(1).
func (Int) CheckedRem ¶ added in v1.0.228
CheckedRem computes the remainder of the Int divided by b, returning None if b is zero or the operation overflows (i == MinInt and b == -1).
func (Int) CheckedSub ¶ added in v1.0.228
CheckedSub subtracts b from the Int, returning None if the subtraction overflows.
func (Int) Clamp ¶ added in v1.0.228
Clamp restricts the Int to the inclusive range [min, max]. The caller must ensure min <= max: this method does not panic on an inverted range — the lower bound is checked first, so the result is unspecified when min > max.
func (Int) Div ¶
Div divides two Ints and returns the result.
Div panics with a runtime "integer divide by zero" error if b is 0. Dividing by zero is treated as a programmer error; guard against a zero divisor at the call site. This differs from Float.Div, which follows IEEE 754 and yields ±Inf or NaN instead of panicking.
func (Int) IsPositive ¶
IsPositive reports whether the Int is strictly greater than zero. Zero is neither positive nor negative: both Int(0).IsPositive() and Int(0).IsNegative() return false. For a non-negative check use !i.IsNegative().
func (Int) Mul ¶
Mul multiplies two Ints and returns the result. Like Go's native arithmetic it wraps on overflow (two's complement). Use CheckedMul, SaturatingMul or OverflowingMul for guarded variants.
func (Int) Neg ¶ added in v1.0.228
Neg returns the Int with its sign inverted. Like Go's native arithmetic it wraps on overflow: Neg of math.MinInt is math.MinInt. Use CheckedNeg for a guarded variant.
func (Int) OverflowingAdd ¶ added in v1.0.228
OverflowingAdd adds two Ints, returning the wrapped result and a flag indicating overflow.
func (Int) OverflowingMul ¶ added in v1.0.228
OverflowingMul multiplies two Ints, returning the wrapped result and a flag indicating overflow.
func (Int) OverflowingSub ¶ added in v1.0.228
OverflowingSub subtracts b from the Int, returning the wrapped result and a flag indicating overflow.
func (Int) Print ¶
Print writes the value of the Int to the standard output (console) and returns the Int unchanged.
func (Int) Println ¶ added in v1.0.122
Println writes the value of the Int to the standard output (console) with a newline and returns the Int unchanged.
func (Int) RandomRange ¶
RandomRange returns a random Int in the inclusive range [i, to]. The order of bounds does not matter (it normalizes to [min, max]). Works for negative bounds and the full int64 range without overflow or bias.
func (Int) Rem ¶
Rem returns the remainder of the division between the receiver and the input value.
Rem panics with a runtime "integer divide by zero" error if b is 0. A zero divisor is treated as a programmer error; guard against it at the call site.
func (Int) SaturatingAdd ¶ added in v1.0.228
SaturatingAdd adds two Ints, clamping the result to MinInt or MaxInt on overflow.
func (Int) SaturatingMul ¶ added in v1.0.228
SaturatingMul multiplies two Ints, clamping the result to MinInt or MaxInt on overflow.
func (Int) SaturatingSub ¶ added in v1.0.228
SaturatingSub subtracts b from the Int, clamping the result to MinInt or MaxInt on overflow.
func (*Int) Scan ¶ added in v1.0.198
Scan implements the database/sql.Scanner interface for g.Int.
Behavior:
- If src is nil, the value is set to 0 (SQL NULL).
- If src is an int64 (common SQL INTEGER type), it is assigned.
- Otherwise, an error is returned.
Supported SQL types (common):
- INTEGER → int64
Notes:
- This allows g.Int to be used directly with database/sql and compatible drivers.
func (Int) Signum ¶ added in v1.0.228
Signum returns the sign of the Int: -1 if the Int is negative, 0 if it is zero, and 1 if it is positive.
func (Int) Sub ¶
Sub subtracts two Ints and returns the result. Like Go's native arithmetic it wraps on overflow (two's complement). Use CheckedSub, SaturatingSub or OverflowingSub for guarded variants.
func (Int) Transform ¶ added in v1.0.89
Transform applies a transformation function to the Int and returns the result.
type Map ¶
type Map[K comparable, V any] map[K]V
Map is a generic alias for a map.
func MapFromPairs ¶ added in v1.0.228
func MapFromPairs[K comparable, V any](pairs Slice[Pair[K, V]]) Map[K, V]
MapFromPairs builds a Map from a slice of pairs. Unlike the variadic MapOf, it takes the slice directly, so it can be passed as a first-class function — e.g. as the collect step after TryMap: res.TryCollect().Map(MapFromPairs).
func MapOf ¶ added in v1.0.228
func MapOf[K comparable, V any](pairs ...Pair[K, V]) Map[K, V]
MapOf creates a Map from the provided key-value pairs.
Example:
m := g.MapOf(g.PairOf("a", 1), g.PairOf("b", 2))
func NewMap ¶
func NewMap[K comparable, V any](size ...Int) Map[K, V]
NewMap creates a new Map of the specified size or an empty Map if no size is provided.
func (Map[K, V]) Insert ¶ added in v1.0.202
Insert sets the value for the key and returns the previous value if it existed.
func (Map[K, V]) Iter ¶
Iter returns an iterator (SeqMap[K, V]) for the Map, allowing for sequential iteration over its key-value pairs. It is commonly used in combination with higher-order functions, such as 'ForEach', to perform operations on each key-value pair of the Map.
Returns:
- SeqMap[K, V], which can be used for sequential iteration over the key-value pairs of the Map.
Example usage:
myMap := g.Map[string, int]{"one": 1, "two": 2, "three": 3}
iterator := myMap.Iter()
iterator.ForEach(func(key string, value int) {
// Perform some operation on each key-value pair
fmt.Printf("%s: %d\n", key, value)
})
The 'Iter' method provides a convenient way to traverse the key-value pairs of a Map in a functional style, enabling operations like mapping or filtering.
func (Map[K, V]) Print ¶
Print writes the key-value pairs of the Map to the standard output (console) and returns the Map unchanged.
func (Map[K, V]) Println ¶ added in v1.0.122
Println writes the key-value pairs of the Map to the standard output (console) with a newline and returns the Map unchanged.
func (Map[K, V]) Remove ¶ added in v1.0.202
Remove removes the specified key from the Map and returns the removed value.
type MapOrd ¶
type MapOrd[K comparable, V any] []Pair[K, V] // ordered key-value pairs
MapOrd is an ordered map that maintains insertion order using a slice of key-value pairs. Key lookups (Get, Insert, Contains, Remove, Entry) scan the slice linearly and are therefore O(n); use Map for O(1) lookups when order is not required.
func MapOrdFromPairs ¶ added in v1.0.228
func MapOrdFromPairs[K comparable, V any](pairs Slice[Pair[K, V]]) MapOrd[K, V]
MapOrdFromPairs builds a MapOrd from a slice of pairs, preserving order. Unlike the variadic MapOrdOf, it takes the slice directly, so it can be passed as a first-class function — e.g. res.TryCollect().Map(MapOrdFromPairs).
func MapOrdFromStd ¶
func MapOrdFromStd[K comparable, V any](m map[K]V) MapOrd[K, V]
MapOrdFromStd converts a standard Go map to an ordered Map. The resulting ordered Map will maintain the order of its key-value pairs based on the order of insertion. This function is useful when you want to create an ordered Map from an existing Go map.
Parameters:
- m map[K]V: The input Go map to be converted to an ordered Map.
Returns:
- MapOrd[K, V]: New ordered Map containing the same key-value pairs as the input Go map.
Example usage:
mapOrd := g.MapOrdFromStd[string, int](goMap)
Converts the standard Go map 'map[K]V' to an ordered Map.
func MapOrdOf ¶ added in v1.0.228
func MapOrdOf[K comparable, V any](pairs ...Pair[K, V]) MapOrd[K, V]
MapOrdOf creates a MapOrd from the provided key-value pairs, preserving their order.
Duplicate keys keep their first-seen position, while the value is updated to the most recent one (last-write-wins).
Example:
mo := g.MapOrdOf(g.PairOf("a", 1), g.PairOf("b", 2))
func NewMapOrd ¶
func NewMapOrd[K comparable, V any](size ...Int) MapOrd[K, V]
NewMapOrd creates a new ordered Map with the specified size (if provided). An ordered Map is an Map that maintains the order of its key-value pairs based on the insertion order. If no size is provided, the default size will be used.
Parameters:
- size ...int: (Optional) The initial size of the ordered Map. If not provided, a default size will be used.
Returns:
- MapOrd[K, V]: Ordered Map with the specified initial size (or default size if not provided).
Example usage:
mapOrd := g.NewMapOrd[string, int](10)
Creates a new ordered Map with an initial size of 10.
func (*MapOrd[K, V]) Clear ¶
func (mo *MapOrd[K, V]) Clear()
Clear removes all key-value pairs from the ordered Map.
func (*MapOrd[K, V]) Copy ¶
Copy copies key-value pairs from the source ordered Map to the current ordered Map.
func (MapOrd[K, V]) Eq ¶
Eq compares the current ordered Map to another ordered Map and returns true if they are equal.
func (MapOrd[K, V]) Get ¶
Get returns the value associated with the given key, wrapped in Option[V].
It returns Some(value) if the key exists, or None if it does not.
func (*MapOrd[K, V]) Insert ¶ added in v1.0.202
Insert sets the value for the specified key in the ordered Map, and returns the previous value if it existed.
func (MapOrd[K, V]) IsSortedBy ¶ added in v1.0.192
IsSortedBy checks if the ordered Map is sorted according to a custom comparison function.
Parameters:
- fn func(a, b Pair[K, V]) cmp.Ordering: The custom comparison function used for checking sort order.
Returns:
- bool: true if the map is sorted according to the comparison function, false otherwise.
Example usage:
sorted := hmapo.IsSortedBy(func(a, b g.Pair[g.String, g.Int]) cmp.Ordering { return a.Key.Cmp(b.Key) })
func (MapOrd[K, V]) IsSortedByKey ¶ added in v1.0.192
IsSortedByKey checks if the ordered MapOrd[K, V] is sorted by the keys using a custom comparison function.
Parameters:
- fn func(a, b K) cmp.Ordering: The custom comparison function used for checking key sort order.
Returns:
- bool: true if the map is sorted by keys according to the comparison function, false otherwise.
Example usage:
sorted := hmapo.IsSortedByKey(func(a, b g.String) cmp.Ordering { return a.Cmp(b) })
func (MapOrd[K, V]) IsSortedByValue ¶ added in v1.0.192
IsSortedByValue checks if the ordered MapOrd[K, V] is sorted by the values using a custom comparison function.
Parameters:
- fn func(a, b V) cmp.Ordering: The custom comparison function used for checking value sort order.
Returns:
- bool: true if the map is sorted by values according to the comparison function, false otherwise.
Example usage:
sorted := hmapo.IsSortedByValue(func(a, b g.Int) cmp.Ordering { return a.Cmp(b) })
func (MapOrd[K, V]) Iter ¶
Iter returns an iterator (SeqMapOrd[K, V]) for the ordered Map, allowing for sequential iteration over its key-value pairs. It is commonly used in combination with higher-order functions, such as 'ForEach', to perform operations on each key-value pair of the ordered Map.
Returns:
A SeqMapOrd[K, V], which can be used for sequential iteration over the key-value pairs of the ordered Map.
Example usage:
m := g.NewMapOrd[int, int]()
m.Insert(1, 1)
m.Insert(2, 2)
m.Insert(3, 3)
m.Iter().ForEach(func(k, v int) {
// Process key-value pair
})
The 'Iter' method provides a convenient way to traverse the key-value pairs of an ordered Map in a functional style, enabling operations like mapping or filtering.
func (MapOrd[K, V]) IterReverse ¶ added in v1.0.96
IterReverse returns an iterator (SeqMapOrd[K, V]) for the ordered Map that allows for sequential iteration over its key-value pairs in reverse order. This method is useful when you need to process the elements from the last to the first.
Returns:
A SeqMapOrd[K, V], which can be used for sequential iteration over the key-value pairs of the ordered Map in reverse order.
Example usage:
m := g.NewMapOrd[int, int]()
m.Insert(1, 1)
m.Insert(2, 2)
m.Insert(3, 3)
m.IterReverse().ForEach(func(k, v int) {
// Process key-value pair in reverse order
fmt.Println("Key:", k, "Value:", v)
})
The 'IterReverse' method complements the 'Iter' method by providing a way to access the elements in a reverse sequence, offering additional flexibility in data processing scenarios.
func (MapOrd[K, V]) Ne ¶
Ne compares the current ordered Map to another ordered Map and returns true if they are not equal.
func (MapOrd[K, V]) Print ¶
Print writes the key-value pairs of the MapOrd to the standard output (console) and returns the MapOrd unchanged.
func (MapOrd[K, V]) Println ¶ added in v1.0.122
Println writes the key-value pairs of the MapOrd to the standard output (console) with a newline and returns the MapOrd unchanged.
func (*MapOrd[K, V]) Remove ¶ added in v1.0.202
Remove removes the specified key from the ordered Map and returns the removed value.
func (MapOrd[K, V]) Shuffle ¶ added in v1.0.88
func (mo MapOrd[K, V]) Shuffle()
Shuffle randomly reorders the elements of the ordered Map. It operates in place and affects the original order of the map's entries.
The function uses the math/rand/v2 package to generate random indices.
func (MapOrd[K, V]) SortBy ¶
SortBy sorts the ordered Map by a custom comparison function.
Parameters:
- fn func(a, b Pair[K, V]) cmp.Ordering: The custom comparison function used for sorting the ordered Map.
Example usage:
hmapo.SortBy(func(a, b g.Pair[g.String, g.Int]) cmp.Ordering { return a.Key.Cmp(b.Key) })
hmapo.SortBy(func(a, b g.Pair[g.String, g.Int]) cmp.Ordering { return a.Value.Cmp(b.Value) })
func (MapOrd[K, V]) SortByKey ¶ added in v1.0.73
SortByKey sorts the ordered MapOrd[K, V] by the keys using a custom comparison function.
Parameters:
- fn func(a, b K) cmp.Ordering: The custom comparison function used for sorting the keys.
Example usage:
hmapo.SortByKey(func(a, b g.String) cmp.Ordering { return a.Cmp(b) })
func (MapOrd[K, V]) SortByValue ¶ added in v1.0.73
SortByValue sorts the ordered MapOrd[K, V] by the values using a custom comparison function.
Parameters:
- fn func(a, b V) cmp.Ordering: The custom comparison function used for sorting the values.
Example usage:
hmapo.SortByValue(func(a, b g.Int) cmp.Ordering { return a.Cmp(b) })
type MapSafe ¶ added in v1.0.111
type MapSafe[K comparable, V any] struct { // contains filtered or unexported fields }
MapSafe is a concurrent-safe generic map built on sync.Map.
func MapSafeFromPairs ¶ added in v1.0.228
func MapSafeFromPairs[K comparable, V any](pairs Slice[Pair[K, V]]) *MapSafe[K, V]
MapSafeFromPairs builds a MapSafe from a slice of pairs. Unlike the variadic MapSafeOf, it takes the slice directly, so it can be passed as a first-class function — e.g. res.TryCollect().Map(MapSafeFromPairs).
func MapSafeOf ¶ added in v1.0.228
func MapSafeOf[K comparable, V any](pairs ...Pair[K, V]) *MapSafe[K, V]
MapSafeOf creates a new MapSafe from the provided key-value pairs. Duplicate keys keep the last-written value, mirroring MapOf / MapOrdOf.
func NewMapSafe ¶ added in v1.0.111
func NewMapSafe[K comparable, V any]() *MapSafe[K, V]
NewMapSafe creates a new instance of MapSafe.
func (*MapSafe[K, V]) Clear ¶ added in v1.0.111
func (ms *MapSafe[K, V]) Clear()
Clear removes all key-value pairs from the MapSafe.
func (*MapSafe[K, V]) Contains ¶ added in v1.0.111
Contains checks if the MapSafe contains the specified key.
func (*MapSafe[K, V]) Copy ¶ added in v1.0.111
Copy performs a deep copy of the source MapSafe's pairs into the current map.
func (*MapSafe[K, V]) Eq ¶ added in v1.0.111
Eq checks if two MapSafes are equal by deep-comparing their values.
func (*MapSafe[K, V]) Get ¶ added in v1.0.111
Get retrieves the value associated with the given key.
func (*MapSafe[K, V]) Insert ¶ added in v1.0.202
Insert stores the value for the given key. Returns Some(previous_value) if the key existed, None if it was newly inserted.
Example:
ms := NewMapSafe[string, int]()
ms.Insert("a", 1) // None (new key)
ms.Insert("a", 2) // Some(1) (replaced)
ms.Get("a").Some() // 2
func (*MapSafe[K, V]) Iter ¶ added in v1.0.111
Iter provides a thread-safe iterator over the MapSafe's key-value pairs.
func (*MapSafe[K, V]) Len ¶ added in v1.0.111
Len returns the number of key-value pairs in the MapSafe.
func (*MapSafe[K, V]) Map ¶ added in v1.0.225
Map converts the MapSafe to a standard Map by taking a snapshot of its current key-value pairs.
The returned Map is an independent, non-thread-safe copy; subsequent mutations to the MapSafe are not reflected in it.
func (*MapSafe[K, V]) Ordered ¶ added in v1.0.225
Ordered converts the MapSafe to an ordered Map by taking a snapshot of its current key-value pairs.
Because MapSafe does not track insertion order, the order of the returned MapOrd is unspecified. The returned MapOrd is an independent, non-thread-safe copy; subsequent mutations to the MapSafe are not reflected in it.
func (*MapSafe[K, V]) Println ¶ added in v1.0.122
Println writes the MapSafe to standard output with a newline.
func (*MapSafe[K, V]) Remove ¶ added in v1.0.202
Remove removes the specified key from the MapSafe and returns the removed value.
func (*MapSafe[K, V]) String ¶ added in v1.0.111
String returns a string representation of the MapSafe.
func (*MapSafe[K, V]) Transform ¶ added in v1.0.225
Transform applies a transformation function to the MapSafe and returns the result.
func (*MapSafe[K, V]) TryInsert ¶ added in v1.0.202
TryInsert inserts value only if the key is absent. Returns Some(existing_value) if key already existed (no insert), None if inserted.
Example:
ms := NewMapSafe[string, int]()
ms.TryInsert("a", 1) // None (inserted)
ms.TryInsert("a", 2) // Some(1) (already existed, not replaced)
ms.Get("a").Some() // 1
type Mutex ¶ added in v1.0.201
type Mutex[T any] struct { // contains filtered or unexported fields }
Mutex is a mutual exclusion lock that protects a value of type T. Unlike sync.Mutex, it binds the protected data to the lock itself, making it impossible to access the data without holding the lock.
A Mutex must not be copied after first use: it embeds a sync.Mutex and a copy would protect a different value than the original (go vet's copylocks analyzer flags such copies). Always pass a *Mutex, never a Mutex by value.
func (*Mutex[T]) Lock ¶ added in v1.0.201
func (m *Mutex[T]) Lock() MutexGuard[T]
Lock acquires the mutex and returns a guard that provides access to the protected value. The caller must call Unlock on the guard when done (typically via defer).
func (*Mutex[T]) TryLock ¶ added in v1.0.201
func (m *Mutex[T]) TryLock() Option[MutexGuard[T]]
TryLock attempts to acquire the mutex without blocking. Returns Some(guard) if successful, None if the mutex is already locked.
type MutexGuard ¶ added in v1.0.201
type MutexGuard[T any] struct { // contains filtered or unexported fields }
MutexGuard provides access to the value protected by a Mutex. The guard must be explicitly unlocked when done.
A guard holds pointers into its owning Mutex; copying the guard and calling Unlock on more than one copy unlocks the same underlying lock twice, which panics. Use each guard exactly once and do not copy it.
func (MutexGuard[T]) Deref ¶ added in v1.0.201
func (g MutexGuard[T]) Deref() *T
Deref returns a pointer to the protected value for direct manipulation.
func (MutexGuard[T]) Get ¶ added in v1.0.201
func (g MutexGuard[T]) Get() T
Get returns a copy of the protected value.
func (MutexGuard[T]) Set ¶ added in v1.0.201
func (g MutexGuard[T]) Set(value T)
Set replaces the protected value with a new one.
func (MutexGuard[T]) Unlock ¶ added in v1.0.201
func (g MutexGuard[T]) Unlock()
Unlock releases the mutex. Must be called when done with the guard.
type Named ¶ added in v1.0.130
Named is a map-like type that stores key-value pairs for resolving named placeholders in Sprintf.
type OccupiedEntry ¶ added in v1.0.200
type OccupiedEntry[K comparable, V any] struct { // contains filtered or unexported fields }
OccupiedEntry represents a view into a map entry that is known to be present.
It is typically obtained from Map.Entry(key) when the key already exists. OccupiedEntry allows inspecting, modifying, replacing, or removing the value associated with the key without performing additional map lookups.
func (OccupiedEntry[K, V]) AndModify ¶ added in v1.0.200
func (e OccupiedEntry[K, V]) AndModify(fn func(*V)) Entry[K, V]
AndModify applies the provided function to the value stored in the map and returns the entry for method chaining.
The function receives a pointer to a copy of the value; after modification, the updated value is written back to the map. The entry must not be used after the same key is externally removed or replaced.
Example:
m.Entry("count").AndModify(func(v *int) { *v++ }).OrInsert(1)
func (OccupiedEntry[K, V]) Get ¶ added in v1.0.200
func (e OccupiedEntry[K, V]) Get() V
Get returns the current value associated with the key.
The value is returned by copy, consistent with Go map semantics.
func (OccupiedEntry[K, V]) Insert ¶ added in v1.0.200
func (e OccupiedEntry[K, V]) Insert(value V) V
Insert replaces the value in the map with the provided one and returns the previous value.
The key remains present in the map.
func (OccupiedEntry[K, V]) Key ¶ added in v1.0.200
func (e OccupiedEntry[K, V]) Key() K
Key returns the key of this occupied entry.
func (OccupiedEntry[K, V]) OrDefault ¶ added in v1.0.200
func (e OccupiedEntry[K, V]) OrDefault() V
OrDefault returns the existing value.
For OccupiedEntry, this is equivalent to Get since the key already exists.
func (OccupiedEntry[K, V]) OrInsert ¶ added in v1.0.200
func (e OccupiedEntry[K, V]) OrInsert(value V) V
OrInsert returns the existing value without modifying the map.
For OccupiedEntry, this is equivalent to Get since the key already exists.
func (OccupiedEntry[K, V]) OrInsertWith ¶ added in v1.0.200
func (e OccupiedEntry[K, V]) OrInsertWith(fn func() V) V
OrInsertWith returns the existing value without invoking the function.
For OccupiedEntry, the function is never called since the key already exists.
func (OccupiedEntry[K, V]) OrInsertWithKey ¶ added in v1.0.200
func (e OccupiedEntry[K, V]) OrInsertWithKey(fn func(K) V) V
OrInsertWithKey returns the existing value without invoking the function.
For OccupiedEntry, the function is never called since the key already exists.
func (OccupiedEntry[K, V]) Remove ¶ added in v1.0.200
func (e OccupiedEntry[K, V]) Remove() V
Remove removes the entry from the map and returns the previously stored value.
After this call, the key is no longer present in the map.
type OccupiedOrdEntry ¶ added in v1.0.200
type OccupiedOrdEntry[K comparable, V any] struct { // contains filtered or unexported fields }
OccupiedOrdEntry represents a view into an ordered map entry that is known to be present.
It is typically obtained from MapOrd.Entry(key) when the key already exists. OccupiedOrdEntry provides access to the key and the value stored in the underlying ordered slice, allowing inspection, modification, replacement, or removal. The key's position is resolved once, when the entry is created, and reused directly by every operation. The entry is therefore only valid as long as the MapOrd is not structurally mutated (Remove, SortBy, Shuffle, Clear) between creation and use; obtain a fresh entry after such mutations.
func (OccupiedOrdEntry[K, V]) AndModify ¶ added in v1.0.200
func (e OccupiedOrdEntry[K, V]) AndModify(fn func(*V)) OrdEntry[K, V]
AndModify applies the provided function to the value stored at the entry's position and returns the entry for method chaining.
The function receives a pointer to the actual value stored in the ordered map, allowing in-place modification.
Example:
m.Entry("count").AndModify(func(v *int) { *v++ }).OrInsert(1)
func (OccupiedOrdEntry[K, V]) Get ¶ added in v1.0.200
func (e OccupiedOrdEntry[K, V]) Get() V
Get returns the current value associated with the key.
The value is returned by copy.
func (OccupiedOrdEntry[K, V]) Insert ¶ added in v1.0.200
func (e OccupiedOrdEntry[K, V]) Insert(value V) V
Insert replaces the value at the entry's position with the provided value and returns the previously stored value.
The position of the entry in the ordered map is preserved.
func (OccupiedOrdEntry[K, V]) Key ¶ added in v1.0.200
func (e OccupiedOrdEntry[K, V]) Key() K
Key returns the key of this occupied entry.
func (OccupiedOrdEntry[K, V]) OrDefault ¶ added in v1.0.200
func (e OccupiedOrdEntry[K, V]) OrDefault() V
OrDefault returns the existing value.
For OccupiedOrdEntry, this is equivalent to Get since the key already exists.
func (OccupiedOrdEntry[K, V]) OrInsert ¶ added in v1.0.200
func (e OccupiedOrdEntry[K, V]) OrInsert(value V) V
OrInsert returns the existing value without modifying the map.
For OccupiedOrdEntry, this is equivalent to Get since the key already exists.
func (OccupiedOrdEntry[K, V]) OrInsertWith ¶ added in v1.0.200
func (e OccupiedOrdEntry[K, V]) OrInsertWith(fn func() V) V
OrInsertWith returns the existing value without invoking the function.
For OccupiedOrdEntry, the function is never called since the key already exists.
func (OccupiedOrdEntry[K, V]) OrInsertWithKey ¶ added in v1.0.200
func (e OccupiedOrdEntry[K, V]) OrInsertWithKey(fn func(K) V) V
OrInsertWithKey returns the existing value without invoking the function.
For OccupiedOrdEntry, the function is never called since the key already exists.
func (OccupiedOrdEntry[K, V]) Remove ¶ added in v1.0.200
func (e OccupiedOrdEntry[K, V]) Remove() V
Remove removes the entry from the ordered map and returns the previously stored value.
This operation preserves the relative order of the remaining entries. After this call, the key is no longer present in the map and the entry must not be used again.
type OccupiedSafeEntry ¶ added in v1.0.200
type OccupiedSafeEntry[K comparable, V any] struct { // contains filtered or unexported fields }
OccupiedSafeEntry represents a view into a concurrent map entry that is known to be present.
It is typically obtained from MapSafe.Entry(key) when the key exists. All operations on OccupiedSafeEntry are safe for concurrent use.
func (OccupiedSafeEntry[K, V]) AndModify ¶ added in v1.0.200
func (e OccupiedSafeEntry[K, V]) AndModify(fn func(*V)) SafeEntry[K, V]
AndModify applies the provided function to the value associated with the key and returns the entry.
The modification is performed using a compare-and-swap loop. The function receives a pointer to a copy of the value; the updated value is written back atomically. Under contention, fn may be invoked more than once before CAS succeeds. It should only modify the provided value and must not rely on exactly-once external side effects.
If the key is concurrently removed, AndModify becomes a no-op.
func (OccupiedSafeEntry[K, V]) Get ¶ added in v1.0.200
func (e OccupiedSafeEntry[K, V]) Get() V
Get returns the current value associated with the key.
If the key is concurrently removed, the zero value of V is returned.
func (OccupiedSafeEntry[K, V]) Insert ¶ added in v1.0.200
func (e OccupiedSafeEntry[K, V]) Insert(value V) V
Insert replaces the value associated with the key and returns the previous value.
The replacement is performed atomically with respect to other map operations.
func (OccupiedSafeEntry[K, V]) Key ¶ added in v1.0.200
func (e OccupiedSafeEntry[K, V]) Key() K
Key returns the key of this entry.
func (OccupiedSafeEntry[K, V]) OrDefault ¶ added in v1.0.200
func (e OccupiedSafeEntry[K, V]) OrDefault() V
OrDefault returns the existing value.
func (OccupiedSafeEntry[K, V]) OrInsert ¶ added in v1.0.200
func (e OccupiedSafeEntry[K, V]) OrInsert(value V) V
OrInsert returns the existing value without modifying the map.
func (OccupiedSafeEntry[K, V]) OrInsertWith ¶ added in v1.0.200
func (e OccupiedSafeEntry[K, V]) OrInsertWith(fn func() V) V
OrInsertWith returns the existing value if present, or inserts the result of fn() and returns it.
Note: Due to concurrent access, fn() may be invoked even if another goroutine inserts the key between the check and insertion. In this case, the result of fn() is discarded and the existing value is returned.
func (OccupiedSafeEntry[K, V]) OrInsertWithKey ¶ added in v1.0.200
func (e OccupiedSafeEntry[K, V]) OrInsertWithKey(fn func(K) V) V
OrInsertWithKey returns the existing value without invoking the function.
func (OccupiedSafeEntry[K, V]) Remove ¶ added in v1.0.200
func (e OccupiedSafeEntry[K, V]) Remove() V
Remove removes the entry from the map and returns the previously stored value.
If the key is concurrently removed, the zero value of V is returned.
type Option ¶
type Option[T any] struct { // contains filtered or unexported fields }
Option is a generic struct for representing an optional value.
func OptionFromPtr ¶ added in v1.0.221
OptionFromPtr converts a pointer into an Option. Returns None if ptr is nil.
func OptionOf ¶ added in v1.0.97
OptionOf creates an Option[T] based on the provided value and a boolean flag. If ok is true, it returns Some(value). Otherwise, it returns None.
func (Option[T]) And ¶ added in v1.0.228
And returns None if the Option is None, otherwise returns other. It is the eager counterpart of Then (which calls a function instead).
func (Option[T]) Expect ¶
Expect returns the value held in the Option. If the Option is None, it panics with the provided message.
func (Option[T]) Filter ¶ added in v1.0.220
Filter returns Some(value) if the Option is Some and the predicate returns true. Otherwise, it returns None.
func (*Option[T]) GetOrInsert ¶ added in v1.0.220
func (o *Option[T]) GetOrInsert(value T) *T
GetOrInsert inserts the given value if the Option is None, and returns a pointer to the contained value. If the Option already contains a value, it is left unchanged.
func (*Option[T]) GetOrInsertWith ¶ added in v1.0.220
func (o *Option[T]) GetOrInsertWith(fn func() T) *T
GetOrInsertWith inserts a value computed by fn if the Option is None, and returns a pointer to the contained value. The function fn is evaluated lazily.
func (*Option[T]) Insert ¶ added in v1.0.220
func (o *Option[T]) Insert(value T) *T
Insert inserts the given value into the Option, replacing any existing value, and returns a pointer to the inserted value.
func (Option[T]) Inspect ¶ added in v1.0.225
Inspect calls fn with the contained value if the Option is Some, then returns the Option unchanged. If the Option is None, fn is not called. It is intended for side effects (logging, debugging) within a chain and never mutates the Option.
func (Option[T]) IsNoneOr ¶ added in v1.0.228
IsNoneOr returns true if the Option is None or the predicate returns true for the contained value. It is the complement of IsSomeAnd.
func (Option[T]) IsSomeAnd ¶ added in v1.0.220
IsSomeAnd returns true if the Option is Some and the predicate returns true for the contained value.
func (Option[T]) Map ¶ added in v1.0.228
Map applies the function fn to the value inside the Option and returns a new Option holding the transformed value. If the Option is None, fn is not called and None is returned. Unlike Then, fn returns a plain U (always Some on a Some input) rather than an Option[U].
func (Option[T]) MapOr ¶ added in v1.0.228
MapOr applies fn to the contained value if Some and returns the result; otherwise returns the provided default value.
func (Option[T]) MapOrElse ¶ added in v1.0.228
MapOrElse applies fn to the contained value if Some and returns the result; otherwise computes and returns the default lazily via defFn.
func (Option[T]) MarshalJSON ¶ added in v1.0.203
MarshalJSON implements the json.Marshaler interface (encoding/json v1) for Option[T]. Some(value) is marshaled as the JSON representation of value. None is marshaled as null.
BREAKING: the implementation is backed by encoding/json/v2, which changes some edge-case semantics compared to the previous encoding/json implementation:
- Some of a nil slice marshals as [] and Some of a nil map marshals as {}, rather than null.
- Strings containing invalid UTF-8 are rejected with an error instead of being silently replaced with U+FFFD.
func (Option[T]) MarshalJSONTo ¶ added in v1.0.228
MarshalJSONTo implements the json.MarshalerTo interface (encoding/json/v2) for Option[T]. encoding/json/v2 prefers this method over MarshalJSON. Some(value) is encoded as the JSON representation of value; None is encoded as null.
Because None and JSON null share one representation, nested Options collapse: Some(None) marshals to null and unmarshals back as None. Wrap the inner Option in a struct (or use Result) when the distinction must survive a round trip.
func (Option[T]) OkOr ¶ added in v1.0.220
OkOr converts the Option into a Result. Returns Ok(value) if Some, otherwise returns Err(err).
func (Option[T]) OkOrElse ¶ added in v1.0.220
OkOrElse converts the Option into a Result. Returns Ok(value) if Some. Otherwise, it calls fn and returns Err(fn()).
func (Option[T]) Option ¶ added in v1.0.184
Option returns the contained value and a boolean reporting whether the Option is Some, conforming to the standard Go comma-ok pattern. If the Option is None, it returns the zero value for T and false.
func (Option[T]) Or ¶ added in v1.0.220
Or returns the Option if it contains a value. Otherwise, it returns the provided alternative Option.
func (Option[T]) OrElse ¶ added in v1.0.220
OrElse returns the Option if it contains a value. Otherwise, it calls fn and returns its result.
func (Option[T]) Ptr ¶ added in v1.0.220
func (o Option[T]) Ptr() *T
Ptr returns a pointer to the contained value if Some. Otherwise, it returns nil.
func (*Option[T]) Replace ¶ added in v1.0.220
Replace replaces the contained value with the given value, returning the old value as an Option. If the Option was None, it inserts the value and returns None.
func (*Option[T]) Scan ¶ added in v1.0.197
Scan implements the database/sql.Scanner interface for Option[T].
Behavior:
- If src is nil, the Option is set to None (SQL NULL).
- If T implements sql.Scanner, its Scan method is used.
- If src can be directly assigned to T, it is assigned as-is.
- Otherwise, common database type conversions are attempted (e.g., int64 → int, []byte → string).
Supported conversions (common SQL types):
- INTEGER → int, int8, int16, int32, int64, uint*
- REAL → float32, float64
- TEXT → string, []byte
- BLOB → []byte
- BOOLEAN → bool
- TIMESTAMP → time.Time
Driver-owned []byte buffers (BLOB/TEXT) are copied before being stored, so the scanned Option keeps a value that is safe to retain across subsequent rows (per the database/sql Scanner contract).
Returns an error if the value cannot be converted to T.
func (Option[T]) Some ¶
func (o Option[T]) Some() T
Some returns the contained value of the Option.
WARNING: If the Option is None, this method will return the zero value for type T. Always check IsSome() before calling this method, or use safer alternatives like Unwrap(), or UnwrapOr().
func (Option[T]) String ¶ added in v1.0.60
String returns a string representation of the Option. If the Option contains a value, it returns a string in the format "Some(value)". Otherwise, it returns "None".
func (*Option[T]) Take ¶ added in v1.0.220
Take takes the value out of the Option, leaving None in its place. It returns Some(value) if the Option was Some, otherwise returns None.
func (Option[T]) Then ¶
Then applies the function fn to the value inside the Option and returns the resulting Option. If the Option is None, fn is not called and None is returned. The result type may differ from the input type.
func (Option[T]) ThenOf ¶ added in v1.0.228
ThenOf applies fn to the value inside the Option and returns a new Option based on the returned (U, bool) comma-ok tuple: ok=true yields Some(value), ok=false yields None. If the Option is None, fn is not called and None is returned. It mirrors Result.ThenOf for the comma-ok idiom.
func (*Option[T]) UnmarshalJSON ¶ added in v1.0.203
UnmarshalJSON implements the json.Unmarshaler interface (encoding/json v1) for Option[T]. JSON null is unmarshaled as None. Any other valid JSON value is unmarshaled as Some(value).
BREAKING: the implementation is backed by encoding/json/v2, which is stricter than the previous encoding/json implementation: duplicate object keys inside the value are rejected, struct field names match case-sensitively, and strings containing invalid UTF-8 are rejected.
func (*Option[T]) UnmarshalJSONFrom ¶ added in v1.0.228
UnmarshalJSONFrom implements the json.UnmarshalerFrom interface (encoding/json/v2) for Option[T]. encoding/json/v2 prefers this method over UnmarshalJSON. JSON null is decoded as None; any other value is decoded into T as Some(value).
func (Option[T]) Unwrap ¶
func (o Option[T]) Unwrap() T
Unwrap returns the value held in the Option. If the Option is None, it panics.
func (Option[T]) UnwrapOr ¶
func (o Option[T]) UnwrapOr(value T) T
UnwrapOr returns the value held in the Option. If the Option is None, it returns the provided default value.
func (Option[T]) UnwrapOrDefault ¶
func (o Option[T]) UnwrapOrDefault() T
UnwrapOrDefault returns the contained value if Some; otherwise returns the zero value for T.
func (Option[T]) Value ¶ added in v1.0.197
Value implements the database/sql/driver.Valuer interface for Option[T].
Behavior:
- If the Option is None, returns nil (SQL NULL).
- If T implements driver.Valuer, its Value method is used.
- If the underlying value is already a valid driver.Value type (int64, float64, bool, []byte, string, time.Time), it is returned directly.
- Otherwise, safe conversions are applied (int → int64, uint → int64, float32 → float64).
Returns an error if the value cannot be converted to a driver.Value.
type OrdEntry ¶ added in v1.0.200
type OrdEntry[K comparable, V any] interface { Key() K OrInsert(value V) V OrInsertWith(fn func() V) V OrInsertWithKey(fn func(K) V) V OrDefault() V AndModify(fn func(*V)) OrdEntry[K, V] // contains filtered or unexported methods }
OrdEntry is a sealed interface representing a view into a single MapOrd entry.
OrdEntry provides an API for in-place manipulation of ordered map entries, enabling efficient "get or insert" patterns without redundant lookups while preserving insertion order.
The interface is sealed to ensure type safety; implementations are limited to OccupiedOrdEntry (when the key exists) and VacantOrdEntry (when the key is absent). Use a type switch to access type-specific methods like Get, Insert, or Remove.
Common usage patterns:
// Increment existing value or insert default
mo.Entry("counter").AndModify(func(v *int) { *v++ }).OrInsert(1)
// Insert only if absent (appends to end)
mo.Entry("key").OrInsert(defaultValue)
// Type switch for fine-grained control
switch e := mo.Entry("key").(type) {
case OccupiedOrdEntry[string, int]:
fmt.Println("exists:", e.Get())
case VacantOrdEntry[string, int]:
e.Insert(42)
}
type Result ¶
type Result[T any] struct { // contains filtered or unexported fields }
Result is a generic struct for representing a result value along with an error.
func CreateTempDir ¶ added in v1.0.228
CreateTempDir creates a new temporary directory in the specified directory with the specified name pattern and returns a Result, which contains a pointer to the Dir or an error if the operation fails. If no directory is specified, the default directory for temporary directories is used. If no name pattern is specified, the default pattern "*" is used.
Parameters:
- args ...String: A variadic parameter specifying the directory and/or name pattern for the temporary directory.
Returns:
- *Dir: A pointer to the Dir representing the temporary directory.
Example usage:
tmpdir := g.CreateTempDir() // Creates a temporary directory with default settings tmpdirWithDir := g.CreateTempDir("mydir") // Creates a temporary directory in "mydir" directory tmpdirWithPattern := g.CreateTempDir("", "tmp") // Creates a temporary directory with "tmp" pattern
func Eprint ¶ added in v1.0.146
Eprint formats according to a format specifier and writes to os.Stderr. It returns a Result containing the number of bytes written or an error.
Example:
g.Eprint("Error: {}", "file not found")
func Eprintln ¶ added in v1.0.146
Eprintln formats according to a format specifier, appends a newline, and writes to os.Stderr. It returns a Result containing the number of bytes written or an error.
Example:
g.Eprintln("Error: {}", "permission denied")
func Print ¶ added in v1.0.122
Print formats according to a format specifier and writes to os.Stdout. It returns a Result containing the number of bytes written or an error.
Example:
g.Print("Hello, {}!\n", "world")
func Println ¶ added in v1.0.122
Println formats according to a format specifier, appends a newline, and writes to os.Stdout. It returns a Result containing the number of bytes written or an error.
Example:
g.Println("Hello, {}", "world")
func ResultOf ¶ added in v1.0.52
ResultOf returns a new Result[T] based on the provided value and error. If err is not nil, it returns an Err Result. Otherwise, it returns an Ok Result.
func TryFormat ¶ added in v1.0.228
TryFormat validates template structure and argument resolution before formatting. Unlike Format, it returns an error for unmatched braces, missing values, malformed modifiers, and unsupported format verbs.
func TryFormatTo ¶ added in v1.0.228
TryFormatTo validates and formats into a temporary buffer, appending to builder only on success so an error never leaves a partial result behind.
func Write ¶ added in v1.0.146
Write formats according to a format specifier and writes to w. It returns a Result containing the number of bytes written or an error.
Example:
res := g.Write(os.Stdout, "Hello, {}!\n", "world")
if res.IsErr() { log.Fatal(res.Err()) }
func Writeln ¶ added in v1.0.146
Writeln formats according to a format specifier, appends a newline, and writes to w. It returns a Result containing the number of bytes written or an error.
Example:
res := g.Writeln(os.Stdout, "Hello, {}", "world")
if res.IsErr() { log.Fatal(res.Err()) }
func (Result[T]) And ¶ added in v1.0.228
And returns the receiver's error if it is Err, otherwise returns other. It is the eager counterpart of Then (which calls a function instead).
func (Result[T]) Err ¶
Err returns the error held in the Result. If the result is Ok, it returns nil.
func (Result[T]) ErrAs ¶ added in v1.0.206
ErrAs finds the first error in Result's error chain that matches target, and if so, sets target to that error value and returns true (using errors.As). Returns false if Result is Ok.
func (Result[T]) ErrIs ¶ added in v1.0.206
ErrIs reports whether the error in Result matches target (using errors.Is). Returns false if Result is Ok.
func (Result[T]) ErrOption ¶ added in v1.0.228
ErrOption returns the contained error as an Option: Some(err) if the Result is Err, or None if it is Ok. It is the error-side counterpart of Option, which returns the Ok value as an Option.
func (Result[T]) ErrSource ¶ added in v1.0.206
ErrSource returns the underlying error wrapped by the Result's error, if any. Returns None if Result is Ok or if the error doesn't wrap another error.
func (Result[T]) Expect ¶
Expect returns the value held in the Result. If the Result is Err, it panics with the provided message.
func (Result[T]) Inspect ¶ added in v1.0.225
Inspect calls fn with the contained value if the Result is Ok, then returns the Result unchanged. If the Result is Err, fn is not called. It is intended for side effects (logging, debugging) within a chain and never mutates the Result.
func (Result[T]) InspectErr ¶ added in v1.0.228
InspectErr calls fn with the contained error if the Result is Err, then returns the Result unchanged. It is the error-side counterpart of Inspect.
func (Result[T]) IsErrAnd ¶ added in v1.0.228
IsErrAnd returns true if the Result is Err and the predicate returns true for the contained error.
func (Result[T]) IsOkAnd ¶ added in v1.0.228
IsOkAnd returns true if the Result is Ok and the predicate returns true for the contained value.
func (Result[T]) Map ¶ added in v1.0.228
Map applies a function to the contained value (if Ok) and returns a new Result holding the transformed value. If the Result is Err, fn is not called and the error is propagated. Unlike Then, fn returns a plain U rather than a Result[U].
func (Result[T]) MapErr ¶ added in v1.0.165
MapErr transforms the error in an Err Result by applying a function to it. It is useful for custom error handling, like replacing one error with another. If the Result is Ok, it does nothing.
func (Result[T]) MapOr ¶ added in v1.0.228
MapOr applies fn to the contained value if Ok and returns the result; otherwise returns the provided default value.
func (Result[T]) MapOrElse ¶ added in v1.0.228
MapOrElse applies fn to the contained value if Ok and returns the result; otherwise computes the default from the error via defFn.
func (Result[T]) MarshalJSON ¶ added in v1.0.228
MarshalJSON implements the json.Marshaler interface (encoding/json v1) for Result[T]. The encoding is externally tagged: Ok(value) is marshaled as {"ok": <json of value>} and Err(err) is marshaled as {"err": "<err.Error()>"}.
If marshaling the contained value fails, that error is returned.
BREAKING: the implementation is backed by encoding/json/v2, which changes some edge-case semantics compared to the previous encoding/json implementation:
- Ok of a nil slice marshals as {"ok":[]} and Ok of a nil map as {"ok":{}}, rather than {"ok":null}.
- Strings containing invalid UTF-8 (in the Ok value or the error message) are rejected with an error instead of being silently replaced with U+FFFD.
NOTE: only the error message is serialized. The concrete error type and any wrapped errors are lost — after a round trip, errors.Is/errors.As chains no longer match.
func (Result[T]) MarshalJSONTo ¶ added in v1.0.228
MarshalJSONTo implements the json.MarshalerTo interface (encoding/json/v2) for Result[T]. encoding/json/v2 prefers this method over MarshalJSON. The encoding matches MarshalJSON: Ok(value) is encoded as {"ok": <json of value>} and Err(err) is encoded as {"err": "<err.Error()>"}.
func (Result[T]) Ok ¶
func (r Result[T]) Ok() T
Ok returns the value held in the Result.
WARNING: If the Result contains an error, this method will return the zero value for type T. Always check IsOk() before calling this method, or use safer alternatives like Result(), UnwrapOr(), or UnwrapOrDefault(). (Unwrap() and Expect() are NOT safe alternatives — they panic on an Err value.)
func (Result[T]) Option ¶ added in v1.0.52
Option converts a Result into an Option. If the Result is Ok, it returns Some(value). If the Result is Err, it returns None.
func (Result[T]) Or ¶ added in v1.0.228
Or returns the Result if it is Ok, otherwise returns the provided alternative Result.
func (Result[T]) OrElse ¶ added in v1.0.228
OrElse returns the Result if it is Ok, otherwise calls fn with the error and returns its result.
func (Result[T]) Result ¶
Result returns the value and error, conforming to the standard Go multi-value return pattern.
func (Result[T]) Then ¶
Then applies a function to the contained value (if Ok) and returns the resulting Result. If the Result is Err, fn is not called and the error is propagated. The result type may differ from the input type.
func (Result[T]) ThenOf ¶ added in v1.0.52
ThenOf applies a function to the contained value (if Ok) and returns a new Result based on the returned (U, error) tuple. If the Result is Err, fn is not called and the error is propagated.
func (*Result[T]) UnmarshalJSON ¶ added in v1.0.228
UnmarshalJSON implements the json.Unmarshaler interface (encoding/json v1) for Result[T]. It expects the externally tagged encoding produced by MarshalJSON: a JSON object with exactly one of the keys "ok" or "err".
BREAKING: the implementation is backed by encoding/json/v2, so duplicate keys are rejected — a document that repeats the same key ({"ok":1,"ok":2}) is now an unmarshal error instead of the previous encoding/json last-wins semantics.
{"err": "msg"} is unmarshaled as Err(errors.New("msg")); the value must be a JSON string. {"ok": <v>} is unmarshaled as Ok with v decoded into T — {"ok": null} decodes null into T following the encoding/json/v2 rules (zero/nil). Anything else (both keys, neither key, extra keys, duplicate keys, a non-object, or JSON null) is an unmarshal error.
NOTE: only the error message survives a round trip. The original error type is not restored — the decoded error is a plain errors.New value, so errors.Is/errors.As chains against the original error no longer match.
func (*Result[T]) UnmarshalJSONFrom ¶ added in v1.0.228
UnmarshalJSONFrom implements the json.UnmarshalerFrom interface (encoding/json/v2) for Result[T]. encoding/json/v2 prefers this method over UnmarshalJSON. It expects a JSON object with exactly one member whose key is "ok" or "err", as produced by MarshalJSONTo.
Duplicate keys are rejected: the strict single-member contract refuses any second object member (a duplicate key included) before the v2 decoder's own duplicate-name check even fires, and the encoding/json/v2 decoder itself forbids duplicate object member names by default. Presence of both distinct keys, extra keys, neither key, a non-object, or JSON null is likewise an unmarshal error.
func (Result[T]) Unwrap ¶
func (r Result[T]) Unwrap() T
Unwrap returns the value held in the Result. If the Result is Err, it panics.
func (Result[T]) UnwrapErr ¶ added in v1.0.228
UnwrapErr returns the contained error. If the Result is Ok, it panics.
func (Result[T]) UnwrapOr ¶
func (r Result[T]) UnwrapOr(value T) T
UnwrapOr returns the value held in the Result. If the Result is Err, it returns the provided default value.
func (Result[T]) UnwrapOrDefault ¶
func (r Result[T]) UnwrapOrDefault() T
UnwrapOrDefault returns the contained value if Ok, otherwise returns the zero value for T.
type RwLock ¶ added in v1.0.201
type RwLock[T any] struct { // contains filtered or unexported fields }
RwLock is a reader-writer lock that protects a value of type T. It allows multiple readers or a single writer at any point in time. Unlike sync.RWMutex, it binds the protected data to the lock itself, making it impossible to access the data without holding the lock.
An RwLock must not be copied after first use: it embeds a sync.RWMutex and a copy would protect a different value than the original (go vet's copylocks analyzer flags such copies). Always pass an *RwLock, never an RwLock by value.
func (*RwLock[T]) RWith ¶ added in v1.0.208
func (r *RwLock[T]) RWith(fn func(T))
RWith acquires a read lock, calls fn with a copy of the protected value, and releases the lock when fn returns. The value is passed by copy to prevent accidental mutation under a read lock.
func (*RwLock[T]) Read ¶ added in v1.0.201
func (r *RwLock[T]) Read() RwLockReadGuard[T]
Read acquires a read lock and returns a guard that provides read-only access. Multiple goroutines can hold read locks simultaneously. The caller must call Unlock on the guard when done (typically via defer).
func (*RwLock[T]) TryRead ¶ added in v1.0.201
func (r *RwLock[T]) TryRead() Option[RwLockReadGuard[T]]
TryRead attempts to acquire a read lock without blocking. Returns Some(guard) if successful, None if a write lock is held.
func (*RwLock[T]) TryWrite ¶ added in v1.0.201
func (r *RwLock[T]) TryWrite() Option[RwLockWriteGuard[T]]
TryWrite attempts to acquire a write lock without blocking. Returns Some(guard) if successful, None if any lock is held.
func (*RwLock[T]) With ¶ added in v1.0.208
func (r *RwLock[T]) With(fn func(*T))
With acquires a write lock, calls fn with a pointer to the protected value, and releases the lock when fn returns. This is a convenience method that eliminates the need for manual Lock/Unlock management.
func (*RwLock[T]) Write ¶ added in v1.0.201
func (r *RwLock[T]) Write() RwLockWriteGuard[T]
Write acquires a write lock and returns a guard that provides exclusive access. No other readers or writers can access the value while this guard exists. The caller must call Unlock on the guard when done (typically via defer).
type RwLockReadGuard ¶ added in v1.0.201
type RwLockReadGuard[T any] struct { // contains filtered or unexported fields }
RwLockReadGuard provides read-only access to the value protected by an RwLock. Multiple read guards can exist simultaneously.
A guard holds pointers into its owning RwLock; copying the guard and calling Unlock on more than one copy releases the same read lock twice, which panics. Use each guard exactly once and do not copy it.
func (RwLockReadGuard[T]) Deref ¶ added in v1.0.201
func (g RwLockReadGuard[T]) Deref() *T
Deref returns a pointer to the protected value for direct access. Note: modifying through this pointer would be a logic error.
func (RwLockReadGuard[T]) Get ¶ added in v1.0.201
func (g RwLockReadGuard[T]) Get() T
Get returns a copy of the protected value.
func (RwLockReadGuard[T]) Unlock ¶ added in v1.0.201
func (g RwLockReadGuard[T]) Unlock()
Unlock releases the read lock. Must be called when done with the guard.
type RwLockWriteGuard ¶ added in v1.0.201
type RwLockWriteGuard[T any] struct { // contains filtered or unexported fields }
RwLockWriteGuard provides exclusive read-write access to the value protected by an RwLock. Only one write guard can exist at a time, and no read guards can coexist with it.
A guard holds pointers into its owning RwLock; copying the guard and calling Unlock on more than one copy releases the same write lock twice, which panics. Use each guard exactly once and do not copy it.
func (RwLockWriteGuard[T]) Deref ¶ added in v1.0.201
func (g RwLockWriteGuard[T]) Deref() *T
Deref returns a pointer to the protected value for direct manipulation.
func (RwLockWriteGuard[T]) Get ¶ added in v1.0.201
func (g RwLockWriteGuard[T]) Get() T
Get returns a copy of the protected value.
func (RwLockWriteGuard[T]) Set ¶ added in v1.0.201
func (g RwLockWriteGuard[T]) Set(value T)
Set replaces the protected value with a new one.
func (RwLockWriteGuard[T]) Unlock ¶ added in v1.0.201
func (g RwLockWriteGuard[T]) Unlock()
Unlock releases the write lock. Must be called when done with the guard.
type SafeEntry ¶ added in v1.0.200
type SafeEntry[K comparable, V any] interface { Key() K OrInsert(value V) V OrInsertWith(fn func() V) V OrInsertWithKey(fn func(K) V) V OrDefault() V AndModify(fn func(*V)) SafeEntry[K, V] // contains filtered or unexported methods }
SafeEntry is a sealed interface representing a view into a single MapSafe entry.
SafeEntry provides an API for in-place manipulation of concurrent map entries, enabling efficient "get or insert" patterns that are safe for concurrent use by multiple goroutines.
The interface is sealed to ensure type safety; implementations are limited to OccupiedSafeEntry (when the key exists) and VacantSafeEntry (when the key is absent). Use a type switch to access type-specific methods like Get, Insert, or Remove.
Concurrency notes:
- AndModify uses a compare-and-swap (CAS) loop for atomic updates
- AndModify may invoke its callback more than once when CAS retries; the callback must not perform non-idempotent external side effects
- VacantSafeEntry stores pending modifications to handle insertion races
- All operations are safe for concurrent use without external locking
Common usage patterns:
// Thread-safe increment or insert (safe for concurrent goroutines)
ms.Entry("counter").AndModify(func(v *int) { *v++ }).OrInsert(1)
// Thread-safe insert only if absent
ms.Entry("key").OrInsert(defaultValue)
// Type switch for fine-grained control
switch e := ms.Entry("key").(type) {
case OccupiedSafeEntry[string, int]:
fmt.Println("exists:", e.Get())
case VacantSafeEntry[string, int]:
e.Insert(42)
}
type SeqDeque ¶ added in v1.0.181
SeqDeque is an iterator over sequences of Deque values.
func (SeqDeque[V]) All ¶ added in v1.0.181
All checks whether all elements in the iterator satisfy the provided condition. This function is useful when you want to determine if all elements in an iterator meet a specific criteria.
Parameters: - fn func(V) bool: A function that returns a boolean indicating whether the element satisfies the condition.
Returns: - bool: True if all elements in the iterator satisfy the condition, false otherwise.
Example usage:
deque := g.DequeOf(1, 2, 3, 4, 5, 6, 7, -1, -2)
isPositive := func(num int) bool { return num > 0 }
allPositive := deque.Iter().All(isPositive)
The resulting allPositive will be true if all elements returned by the iterator are positive.
func (SeqDeque[V]) Any ¶ added in v1.0.181
Any checks whether any element in the iterator satisfies the provided condition. This function is useful when you want to determine if at least one element in an iterator meets a specific criteria.
Parameters: - fn func(V) bool: A function that returns a boolean indicating whether the element satisfies the condition.
Returns: - bool: True if at least one element in the iterator satisfies the condition, false otherwise.
Example usage:
deque := g.DequeOf(1, 3, 5, 7, 9)
isEven := func(num int) bool { return num%2 == 0 }
anyEven := deque.Iter().Any(isEven)
The resulting anyEven will be true if at least one element returned by the iterator is even.
func (SeqDeque[V]) Chain ¶ added in v1.0.181
Chain concatenates the current iterator with other iterators, returning a new iterator.
The function creates a new iterator that combines the elements of the current iterator with elements from the provided iterators in the order they are given.
Params:
- seqs ([]SeqDeque[V]): Other iterators to be concatenated with the current iterator.
Returns:
- SeqDeque[V]: A new iterator containing elements from the current iterator and the provided iterators.
Example usage:
iter1 := g.DequeOf(1, 2, 3).Iter() iter2 := g.DequeOf(4, 5, 6).Iter() iter1.Chain(iter2).Collect().Print()
Output: Deque[1, 2, 3, 4, 5, 6]
The resulting iterator will contain elements from both iterators in the specified order.
func (SeqDeque[V]) Chan ¶ added in v1.0.205
Chan converts the iterator into a channel, optionally with context(s).
The function converts the elements of the iterator into a channel for streaming purposes. Optionally, it accepts context(s) to handle cancellation or timeout scenarios.
Params:
- ctxs (context.Context): Optional context(s) to control the channel behavior (e.g., cancellation).
Returns:
- chan V: A channel containing the elements from the iterator.
Warning: when no context is supplied, the default is context.Background(), which never cancels. The producer goroutine then blocks on send until every element is consumed; if the consumer abandons the channel early (e.g. breaks out of the range loop), that goroutine leaks. Pass a cancelable context and cancel it when you stop consuming to avoid the leak.
Example usage:
iter := g.DequeOf(1, 2, 3).Iter()
ctx, cancel := context.WithCancel(context.Background())
defer cancel() // Ensure cancellation to avoid goroutine leaks.
ch := iter.Chan(ctx)
for val := range ch {
fmt.Println(val)
}
The resulting channel allows streaming elements from the iterator with optional context handling.
func (SeqDeque[V]) ChunkBy ¶ added in v1.0.228
ChunkBy groups CONSECUTIVE elements of the sequence into chunks based on a custom equality function. It is not an SQL-style GroupBy: elements are never reordered or bucketed by key, so equal elements that are not adjacent end up in different chunks.
The provided function `fn` takes two consecutive elements `a` and `b` and returns `true` if they belong to the same chunk, or `false` if a new chunk should start. The function returns a `SeqSlices[V]`, where each `[]V` represents a run of consecutive elements that satisfy the provided equality condition.
Notes:
- Each chunk is returned as a copy of the elements, since `SeqDeque` does not guarantee that elements share the same backing array.
Parameters:
- fn (func(a, b V) bool): Function that determines whether two consecutive elements belong to the same chunk.
Returns:
- SeqSlices[V]: An iterator yielding slices, each containing one chunk.
Example usage:
deque := g.DequeOf(1, 1, 2, 3, 2, 3, 4)
chunks := deque.Iter().ChunkBy(func(a, b int) bool { return a <= b }).Collect()
// Output: [Slice[1, 1, 2, 3] Slice[2, 3, 4]]
The resulting iterator will yield runs of consecutive elements according to the provided function.
func (SeqDeque[V]) Chunks ¶ added in v1.0.181
Chunks returns an iterator that yields chunks of elements of the specified size.
The function creates a new iterator that yields chunks of elements from the original iterator, with each chunk containing elements of the specified size.
Params:
- n (Int): The size of each chunk.
Returns:
- SeqSlices[V]: An iterator yielding chunks of elements of the specified size.
Example usage:
deque := g.DequeOf(1, 2, 3, 4, 5, 6) chunks := deque.Iter().Chunks(2).Collect()
Output: [Slice[1, 2] Slice[3, 4] Slice[5, 6]]
The resulting iterator will yield chunks of elements, each containing the specified number of elements.
func (SeqDeque[V]) Collect ¶ added in v1.0.181
Collect gathers all elements from the iterator into a Deque.
func (SeqDeque[V]) Combinations ¶ added in v1.0.181
Combinations generates all combinations of length 'n' from the sequence.
func (SeqDeque[V]) Context ¶ added in v1.0.181
Context allows the iteration to be controlled with a context.Context.
func (SeqDeque[V]) Count ¶ added in v1.0.181
Count consumes the iterator, counting the number of iterations and returning it.
func (SeqDeque[V]) CounterBy ¶ added in v1.0.228
func (seq SeqDeque[V]) CounterBy[K comparable](fn func(V) K) SeqMapOrd[K, Int]
CounterBy consumes the sequence and returns an ordered map from fn(element) to the number of elements that produced that key: fn is applied to every element, and elements whose keys collide are merged into one bucket with their counts summed. Key order is first-seen. The key type must be comparable; for identity counting pass the identity function (func(v V) V { return v }).
Example usage:
words.Iter().CounterBy(func(w String) Int { return w.Len() })
// MapOrd{5:2, 4:1} — counts by word length, in first-seen order
func (SeqDeque[V]) Cycle ¶ added in v1.0.181
Cycle returns an iterator that endlessly repeats the elements of the current sequence.
func (SeqDeque[V]) Dedup ¶ added in v1.0.181
Dedup creates a new iterator that removes consecutive duplicate elements from the original iterator, leaving only one occurrence of each unique element. If the iterator is sorted, all elements will be unique.
Parameters: - None
Returns: - SeqDeque[V]: A new iterator with consecutive duplicates removed.
Example usage:
deque := g.DequeOf(1, 2, 2, 3, 4, 4, 4, 5) iter := deque.Iter().Dedup() result := iter.Collect() result.Print()
Output: Deque[1, 2, 3, 4, 5]
The resulting iterator will contain only unique elements, removing consecutive duplicates.
func (SeqDeque[V]) Enumerate ¶ added in v1.0.181
Enumerate adds an index to each element in the iterator.
Returns:
- SeqMapOrd[Int, V] An iterator with each element of type Pair[Int, V], where the first element of the pair is the index and the second element is the original element from the iterator.
Example usage:
ps := g.DequeOf("bbb", "ddd", "xxx", "aaa", "ccc").
Iter().
Enumerate().
Collect()
ps.Print()
Output: MapOrd{0:bbb, 1:ddd, 2:xxx, 3:aaa, 4:ccc}
func (SeqDeque[V]) Exclude ¶ added in v1.0.181
Exclude returns a new iterator excluding elements that satisfy the provided function.
The function applies the provided function to each element of the iterator. If the function returns true for an element, that element is excluded from the resulting iterator.
Parameters:
- fn (func(V) bool): The function to be applied to each element of the iterator to determine if it should be excluded from the result.
Returns:
- SeqDeque[V]: A new iterator containing the elements that do not satisfy the given condition.
Example usage:
deque := g.DequeOf(1, 2, 3, 4, 5)
notEven := deque.Iter().
Exclude(
func(val int) bool {
return val%2 == 0
}).
Collect()
notEven.Print()
Output: Deque[1, 3, 5]
The resulting iterator will contain only the elements that do not satisfy the provided function.
func (SeqDeque[V]) Filter ¶ added in v1.0.181
Filter returns a new iterator containing only the elements that satisfy the provided function.
The function applies the provided function to each element of the iterator. If the function returns true for an element, that element is included in the resulting iterator.
Parameters:
- fn (func(V) bool): The function to be applied to each element of the iterator to determine if it should be included in the result.
Returns:
- SeqDeque[V]: A new iterator containing the elements that satisfy the given condition.
Example usage:
deque := g.DequeOf(1, 2, 3, 4, 5)
even := deque.Iter().
Filter(
func(val int) bool {
return val%2 == 0
}).
Collect()
even.Print()
Output: Deque[2, 4].
The resulting iterator will contain only the elements that satisfy the provided function.
func (SeqDeque[V]) FilterMap ¶ added in v1.0.184
FilterMap applies a function to each element and filters out None results.
The function transforms and filters elements in a single pass. Elements where the function returns None are filtered out, and elements where it returns Some are unwrapped and included in the result.
Params:
- fn (func(V) Option[V]): The function that transforms and filters elements. Returns Some(value) to include the transformed element, or None to filter it out.
Returns:
- SeqDeque[V]: A sequence containing only the successfully transformed elements.
Example usage:
deque := g.DequeOf(1, 2, 3, 4, 5)
result := deque.Iter().FilterMap(func(n int) g.Option[int] {
if n%2 == 0 {
return g.Some(n * 10)
}
return g.None[int]()
}).Collect()
result.Print() // Deque[20, 40]
func (SeqDeque[V]) Find ¶ added in v1.0.181
Find searches for an element in the iterator that satisfies the provided function.
The function iterates through the elements of the iterator and returns the first element for which the provided function returns true.
Params:
- fn (func(V) bool): The function used to test elements for a condition.
Returns:
- Option[V]: An Option containing the first element that satisfies the condition; None if not found.
Example usage:
iter := g.DequeOf(1, 2, 3, 4, 5).Iter()
found := // func(i int) bool {
return i == 2
}.Find()
if found.IsSome() {
fmt.Println("Found:", found.Some())
} else {
fmt.Println("Not found.")
}
The resulting Option may contain the first element that satisfies the condition, or None if not found.
func (SeqDeque[V]) FindMap ¶ added in v1.0.228
FindMap applies fn to each element and returns the first Some result, or None if fn returns None for every element.
func (SeqDeque[V]) FlatMap ¶ added in v1.0.184
FlatMap applies a function to each element and flattens the results into a single sequence.
The function transforms each element into a new SeqDeque and then flattens all resulting sequences into a single sequence.
Params:
- fn (func(V) SeqDeque[V]): The function that transforms each element into a SeqDeque.
Returns:
- SeqDeque[V]: A flattened sequence containing all elements from the transformed sequences.
Example usage:
deque := g.DequeOf(1, 2, 3)
result := deque.Iter().FlatMap(func(n int) g.SeqDeque[int] {
return g.DequeOf(n, n*10).Iter()
}).Collect()
result.Print() // Deque[1, 10, 2, 20, 3, 30]
func (SeqDeque[V]) Flatten ¶ added in v1.0.181
Flatten flattens an iterator containing slices into a single iterator.
The function creates a new iterator that flattens a sequence of iterators, returning a single iterator containing elements from each iterator in sequence.
Returns:
- SeqDeque[V]: A single iterator containing elements from the sequence of iterators.
Example usage:
nestedDeque := g.DequeOf(
1,
g.SliceOf(2, 3),
"abc",
g.SliceOf("def", "ghi"),
g.SliceOf(4.5, 6.7),
)
nestedDeque.Iter().Flatten().Collect().Print()
Output: Deque[1, 2, 3, abc, def, ghi, 4.5, 6.7]
The resulting iterator will contain elements from each iterator in sequence.
func (SeqDeque[V]) Fold ¶ added in v1.0.181
Fold accumulates values in the iterator using a function.
The function iterates through the elements of the iterator, accumulating values using the provided function and an initial value.
Params:
- init (V): The initial value for accumulation.
- fn (func(V, V) V): The function that accumulates values; it takes two arguments of type V and returns a value of type V.
Returns:
- T: The accumulated value after applying the function to all elements.
Example usage:
deque := g.DequeOf(1, 2, 3, 4, 5)
sum := deque.Iter().
Fold(0,
func(acc, val int) int {
return acc + val
})
fmt.Println(sum)
Output: 15.
The resulting value will be the accumulation of elements based on the provided function.
func (SeqDeque[V]) ForEach ¶ added in v1.0.181
func (seq SeqDeque[V]) ForEach(fn func(v V))
ForEach iterates through all elements and applies the given function to each.
The function applies the provided function to each element of the iterator.
Params:
- fn (func(V)): The function to apply to each element.
Example usage:
iter := g.DequeOf(1, 2, 3, 4, 5).Iter()
func(val V) {
fmt.Println(val) // Replace this with the function logic you need.
}.ForEach()
The provided function will be applied to each element in the iterator.
func (SeqDeque[V]) Inspect ¶ added in v1.0.181
Inspect creates a new iterator that wraps around the current iterator and allows inspecting each element as it passes through.
func (SeqDeque[V]) Intersperse ¶ added in v1.0.181
Intersperse inserts the provided separator between elements of the iterator.
The function creates a new iterator that inserts the given separator between each consecutive pair of elements in the original iterator.
Params:
- sep (V): The separator to intersperse between elements.
Returns:
- SeqDeque[V]: An iterator containing elements with the separator interspersed.
Example usage:
g.DequeOf("Hello", "World", "!").
Iter().
Intersperse(" ").
Collect().
Print()
Output: "Hello World !".
The resulting iterator will contain elements with the separator interspersed.
func (SeqDeque[V]) Map ¶ added in v1.0.181
Map transforms each element in the iterator using the given function.
The function creates a new iterator by applying the provided function to each element of the original iterator.
Params:
- fn (func(V) V): The function used to transform elements.
Returns:
- SeqDeque[V]: A iterator containing elements transformed by the provided function.
Example usage:
deque := g.DequeOf(1, 2, 3)
doubled := deque.
Iter().
Map(
func(val int) int {
return val * 2
}).
Collect()
doubled.Print()
Output: Deque[2, 4, 6].
The resulting iterator will contain elements transformed by the provided function.
func (SeqDeque[V]) MaxBy ¶ added in v1.0.181
MaxBy returns the maximum element in the sequence using the provided comparison function.
func (SeqDeque[V]) MinBy ¶ added in v1.0.181
MinBy returns the minimum element in the sequence using the provided comparison function.
func (*SeqDeque[V]) Next ¶ added in v1.0.189
Next extracts the next element from the iterator and advances it.
This method consumes the next element from the iterator and returns it wrapped in an Option. The iterator itself is modified to point to the remaining elements.
Returns: - Option[V]: Some(value) if an element exists, None if the iterator is exhausted.
func (SeqDeque[V]) Partition ¶ added in v1.0.181
Partition divides the elements of the iterator into two separate deques based on a given predicate function.
The function takes a predicate function 'fn', which should return true or false for each element in the iterator. Elements for which 'fn' returns true are collected into the left deque, while those for which 'fn' returns false are collected into the right deque.
Params:
- fn (func(V) bool): The predicate function used to determine the placement of elements.
Returns:
- (Deque[V], Deque[V]): Two deques representing elements that satisfy and don't satisfy the predicate, respectively.
Example usage:
evens, odds := g.DequeOf(1, 2, 3, 4, 5).
Iter().
Partition(
func(v int) bool {
return v%2 == 0
})
fmt.Println("Even numbers:", evens) // Output: Even numbers: Deque[2, 4]
fmt.Println("Odd numbers:", odds) // Output: Odd numbers: Deque[1, 3, 5]
The resulting two deques will contain elements separated based on whether they satisfy the predicate or not.
func (SeqDeque[V]) Permutations ¶ added in v1.0.181
Permutations generates iterators of all permutations of elements.
The function uses a recursive approach to generate all the permutations of the elements. If the iterator is empty or contains a single element, it returns the iterator itself wrapped in a single-element iterator.
Returns:
- SeqSlices[V]: An iterator of iterators containing all possible permutations of the elements in the iterator.
Example usage:
deque := g.DequeOf(1, 2, 3)
perms := deque.Iter().Permutations().Collect()
for _, perm := range perms {
fmt.Println(perm)
}
Output: Slice[1, 2, 3] Slice[2, 1, 3] Slice[3, 1, 2] Slice[1, 3, 2] Slice[2, 3, 1] Slice[3, 2, 1]
The resulting iterator will contain iterators representing all possible permutations of the elements in the original iterator.
func (SeqDeque[V]) ProductBy ¶ added in v1.0.228
func (seq SeqDeque[V]) ProductBy[S constraints.Number](fn func(V) S) S
ProductBy maps each element to a numeric value via fn and returns their product. An empty sequence yields the multiplicative identity, one.
func (SeqDeque[V]) Pull ¶ added in v1.0.181
Pull converts the "push-style" iterator sequence seq into a "pull-style" iterator accessed by the two functions next and stop.
Next returns the next value in the sequence and a boolean indicating whether the value is valid. When the sequence is over, next returns the zero V and false. It is valid to call next after reaching the end of the sequence or after calling stop. These calls will continue to return the zero V and false.
Stop ends the iteration. It must be called when the caller is no longer interested in next values and next has not yet signaled that the sequence is over (with a false boolean return). It is valid to call stop multiple times and when next has already returned false.
It is an error to call next or stop from multiple goroutines simultaneously.
func (SeqDeque[V]) Range ¶ added in v1.0.181
Range iterates through elements until the given function returns false.
The function iterates through the elements of the iterator and applies the provided function to each element. It stops iteration when the function returns false for an element.
Params:
- fn (func(V) bool): The function that evaluates elements for continuation of iteration.
Example usage:
iter := g.DequeOf(1, 2, 3, 4, 5).Iter()
func(val int) bool {
fmt.Println(val) // Replace this with the function logic you need.
return val < 5 // Replace this with the condition for continuing iteration.
}.Range()
The iteration will stop when the provided function returns false for an element.
func (SeqDeque[V]) Reduce ¶ added in v1.0.181
Reduce aggregates elements of the sequence using the provided function. The first element of the sequence is used as the initial accumulator value. If the sequence is empty, it returns None[V].
Params:
- fn (func(V, V) V): Function that combines two values into one.
Returns:
- Option[V]: The accumulated value wrapped in Some, or None if the sequence is empty.
Example:
deque := g.DequeOf(1, 2, 3, 4, 5)
product := deque.Iter().Reduce(func(a, b int) int { return a * b })
if product.IsSome() {
fmt.Println(product.Some()) // 120
} else {
fmt.Println("empty")
}
func (SeqDeque[V]) Scan ¶ added in v1.0.184
Scan applies a function to each element and produces a sequence of successive accumulated results.
The function takes an initial value and applies the provided function to each element along with the accumulated value, producing a new sequence where each element is the result of the accumulation. The initial value is included as the first element.
Params:
- init (V): The initial value for the accumulation.
- fn (func(acc, val V) V): The function that combines the accumulator with each element.
Returns:
- SeqDeque[V]: A sequence containing the initial value and all accumulated results.
Example usage:
deque := g.DequeOf(1, 2, 3, 4, 5)
result := deque.Iter().Scan(0, func(acc, val int) int {
return acc + val
}).Collect()
result.Print() // Deque[0, 1, 3, 6, 10, 15]
func (SeqDeque[V]) Skip ¶ added in v1.0.181
Skip returns a new iterator skipping the first n elements.
The function creates a new iterator that skips the first n elements of the current iterator and returns an iterator starting from the (n+1)th element.
Params:
- n (uint): The number of elements to skip from the beginning of the iterator.
Returns:
- SeqDeque[V]: An iterator that starts after skipping the first n elements.
Example usage:
iter := g.DequeOf(1, 2, 3, 4, 5, 6).Iter() 3.Skip().Collect().Print()
Output: Deque[4, 5, 6]
The resulting iterator will start after skipping the specified number of elements.
func (SeqDeque[V]) SkipWhile ¶ added in v1.0.228
SkipWhile skips elements while the predicate returns true, then yields the rest.
func (SeqDeque[V]) SortBy ¶ added in v1.0.181
SortBy applies a custom sorting function to the elements in the iterator and returns a new iterator containing the sorted elements.
The sorting function 'fn' should take two arguments, 'a' and 'b' of type V, and return true if 'a' should be ordered before 'b', and false otherwise.
Example:
g.DequeOf("a", "c", "b").
Iter().
SortBy(func(a, b string) cmp.Ordering { return b.Cmp(a) }).
Collect().
Print()
Output: Deque[c, b, a]
The returned iterator is of type SeqDeque[V], which implements the iterator interface for further iteration over the sorted elements.
func (SeqDeque[V]) StepBy ¶ added in v1.0.181
StepBy creates a new iterator that iterates over every N-th element of the original iterator. This function is useful when you want to skip a specific number of elements between each iteration.
Parameters: - n uint: The step size, indicating how many elements to skip between each iteration.
Returns: - SeqDeque[V]: A new iterator that produces elements from the original iterator with a step size of N.
Example usage:
deque := g.DequeOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10) iter := deque.Iter().StepBy(3) result := iter.Collect() result.Print()
Output: Deque[1, 4, 7, 10]
The resulting iterator will produce elements from the original iterator with a step size of N.
func (SeqDeque[V]) SumBy ¶ added in v1.0.228
func (seq SeqDeque[V]) SumBy[S constraints.Number](fn func(V) S) S
SumBy maps each element to a numeric value via fn and returns the sum of those values. An empty sequence yields the zero value of S.
func (SeqDeque[V]) Take ¶ added in v1.0.181
Take returns a new iterator with the first n elements. The function creates a new iterator containing the first n elements from the original iterator.
func (SeqDeque[V]) TakeWhile ¶ added in v1.0.228
TakeWhile yields elements while the predicate returns true, stopping at the first false.
func (SeqDeque[V]) TryMap ¶ added in v1.0.228
TryMap applies a fallible transform to each element and enters the Result pipeline, producing a SeqResult[U]. See SeqSlice.TryMap for the full contract (lazy, consumer-driven; terminals decide the Err policy).
func (SeqDeque[V]) Unique ¶ added in v1.0.181
Unique returns an iterator with only unique elements.
The function returns an iterator containing only the unique elements from the original iterator.
Returns:
- SeqDeque[V]: An iterator containing unique elements from the original iterator.
Example usage:
deque := g.DequeOf(1, 2, 3, 2, 4, 5, 3) unique := deque.Iter().Unique().Collect() unique.Print()
Output: Deque[1, 2, 3, 4, 5].
The resulting iterator will contain only unique elements from the original iterator.
func (SeqDeque[V]) Windows ¶ added in v1.0.181
Windows returns an iterator that yields sliding windows of elements of the specified size.
The function creates a new iterator that yields windows of elements from the original iterator, where each window is a slice containing elements of the specified size and moves one element at a time.
Params:
- n (int): The size of each window.
Returns:
- SeqSlices[V]: An iterator yielding sliding windows of elements of the specified size.
Example usage:
deque := g.DequeOf(1, 2, 3, 4, 5, 6) windows := deque.Iter().Windows(3).Collect()
Output: [Slice[1, 2, 3] Slice[2, 3, 4] Slice[3, 4, 5] Slice[4, 5, 6]]
The resulting iterator will yield sliding windows of elements, each containing the specified number of elements.
type SeqHeap ¶ added in v1.0.181
SeqHeap is an iterator over sequences of Heap values.
func (SeqHeap[V]) All ¶ added in v1.0.181
All checks whether all elements in the iterator satisfy the provided condition. This function is useful when you want to determine if all elements in an iterator meet a specific criteria.
Parameters: - fn func(V) bool: A function that returns a boolean indicating whether the element satisfies the condition.
Returns: - bool: True if all elements in the iterator satisfy the condition, false otherwise.
Example usage:
heap := g.NewHeap(cmp.Cmp[int])
heap.Push(1, 2, 3, 4, 5, 6, 7, -1, -2)
isPositive := func(num int) bool { return num > 0 }
allPositive := heap.Iter().All(isPositive)
The resulting allPositive will be true if all elements returned by the iterator are positive.
func (SeqHeap[V]) Any ¶ added in v1.0.181
Any checks whether any element in the iterator satisfies the provided condition. This function is useful when you want to determine if at least one element in an iterator meets a specific criteria.
Parameters: - fn func(V) bool: A function that returns a boolean indicating whether the element satisfies the condition.
Returns: - bool: True if at least one element in the iterator satisfies the condition, false otherwise.
Example usage:
heap := g.NewHeap(cmp.Cmp[int])
heap.Push(1, 3, 5, 7, 9)
isEven := func(num int) bool { return num%2 == 0 }
anyEven := heap.Iter().Any(isEven)
The resulting anyEven will be true if at least one element returned by the iterator is even.
func (SeqHeap[V]) Chain ¶ added in v1.0.181
Chain concatenates the current iterator with other iterators, returning a new iterator.
The function creates a new iterator that combines the elements of the current iterator with elements from the provided iterators in the order they are given.
Params:
- seqs ([]SeqHeap[V]): Other iterators to be concatenated with the current iterator.
Returns:
- SeqHeap[V]: A new iterator containing elements from the current iterator and the provided iterators.
Example usage:
heap1 := g.NewHeap(cmp.Cmp[int]) heap1.Push(1, 2, 3) heap2 := g.NewHeap(cmp.Cmp[int]) heap2.Push(4, 5, 6) heap1.Iter().Chain(heap2.Iter()).Collect(cmp.Cmp[int]) // Creates new heap with all elements
The resulting iterator will contain elements from both iterators in the specified order.
func (SeqHeap[V]) Chan ¶ added in v1.0.205
Chan converts the iterator into a channel, optionally with context(s).
The function converts the elements of the iterator into a channel for streaming purposes. Optionally, it accepts context(s) to handle cancellation or timeout scenarios.
Params:
- ctxs (context.Context): Optional context(s) to control the channel behavior (e.g., cancellation).
Returns:
- chan V: A channel containing the elements from the iterator.
Example usage:
heap := g.NewHeap(cmp.Cmp[int])
heap.Push(1, 2, 3)
ctx, cancel := context.WithCancel(context.Background())
defer cancel() // Ensure cancellation to avoid goroutine leaks.
ch := heap.Iter().Chan(ctx)
for val := range ch {
fmt.Println(val)
}
The resulting channel allows streaming elements from the iterator with optional context handling.
func (SeqHeap[V]) ChunkBy ¶ added in v1.0.228
ChunkBy groups CONSECUTIVE elements of the sequence into chunks based on a custom equality function. It is not an SQL-style GroupBy: elements are never reordered or bucketed by key, so equal elements that are not adjacent end up in different chunks.
The provided function `fn` takes two consecutive elements `a` and `b` and returns `true` if they belong to the same chunk, or `false` if a new chunk should start. The function returns a `SeqSlices[V]`, where each `[]V` represents a run of consecutive elements that satisfy the provided equality condition.
Notes:
- Each chunk is returned as a copy of the elements, since `SeqHeap` does not guarantee that elements share the same backing array.
Parameters:
- fn (func(a, b V) bool): Function that determines whether two consecutive elements belong to the same chunk.
Returns:
- SeqSlices[V]: An iterator yielding slices, each containing one chunk.
Example usage:
heap := g.NewHeap(cmp.Cmp[int])
heap.Push(1, 1, 2, 3, 2, 3, 4)
chunks := heap.Iter().ChunkBy(func(a, b int) bool { return a <= b }).Collect()
// Output: [Slice[1, 1, 2, 3] Slice[2, 3, 4]]
The resulting iterator will yield runs of consecutive elements according to the provided function.
func (SeqHeap[V]) Chunks ¶ added in v1.0.181
Chunks returns an iterator that yields chunks of elements of the specified size.
The function creates a new iterator that yields chunks of elements from the original iterator, with each chunk containing elements of the specified size.
Params:
- n (Int): The size of each chunk.
Returns:
- SeqSlices[V]: An iterator yielding chunks of elements of the specified size.
Example usage:
heap := g.NewHeap(cmp.Cmp[int]) heap.Push(1, 2, 3, 4, 5, 6) chunks := heap.Iter().Chunks(2).Collect()
Output: [Slice[1, 2] Slice[3, 4] Slice[5, 6]]
The resulting iterator will yield chunks of elements, each containing the specified number of elements.
func (SeqHeap[V]) Collect ¶ added in v1.0.181
Collect gathers all elements from the iterator into a new Heap with a custom comparison function.
Note: the comparator argument is required because SeqHeap is a purely functional sequence type — it carries only the yielded elements, so the source heap's comparator cannot travel through adapters such as Map or Filter and must be supplied again when a new Heap is built. Partition shares the same characteristic (it takes leftCmp and rightCmp).
func (SeqHeap[V]) Combinations ¶ added in v1.0.181
Combinations generates all combinations of length 'n' from the sequence.
func (SeqHeap[V]) Context ¶ added in v1.0.181
Context allows the iteration to be controlled with a context.Context.
func (SeqHeap[V]) Count ¶ added in v1.0.181
Count consumes the iterator, counting the number of iterations and returning it.
func (SeqHeap[V]) CounterBy ¶ added in v1.0.228
func (seq SeqHeap[V]) CounterBy[K comparable](fn func(V) K) SeqMapOrd[K, Int]
CounterBy consumes the sequence and returns an ordered map from fn(element) to the number of elements that produced that key: fn is applied to every element, and elements whose keys collide are merged into one bucket with their counts summed. Key order is first-seen. The key type must be comparable; for identity counting pass the identity function (func(v V) V { return v }).
Example usage:
words.Iter().CounterBy(func(w String) Int { return w.Len() })
// MapOrd{5:2, 4:1} — counts by word length, in first-seen order
func (SeqHeap[V]) Cycle ¶ added in v1.0.181
Cycle returns an iterator that endlessly repeats the elements of the current sequence.
func (SeqHeap[V]) Dedup ¶ added in v1.0.181
Dedup creates a new iterator that removes consecutive duplicate elements from the original iterator, leaving only one occurrence of each unique element. If the iterator is sorted, all elements will be unique.
Parameters: - None
Returns: - SeqHeap[V]: A new iterator with consecutive duplicates removed.
Example usage:
heap := g.NewHeap(cmp.Cmp[int])
heap.Push(1, 2, 2, 3, 4, 4, 4, 5)
iter := heap.Iter().Dedup()
result := iter.Collect(cmp.Cmp[int])
result.Iter().ForEach(func(v int) { fmt.Print(v, " ") })
Output: 1 2 3 4 5
The resulting iterator will contain only unique elements, removing consecutive duplicates.
func (SeqHeap[V]) Enumerate ¶ added in v1.0.181
Enumerate adds an index to each element in the iterator.
Returns:
- SeqMapOrd[Int, V] An iterator with each element of type Pair[Int, V], where the first element of the pair is the index and the second element is the original element from the iterator.
Example usage:
heap := g.NewHeap(cmp.Cmp[g.String])
heap.Push("bbb", "ddd", "xxx", "aaa", "ccc")
ps := heap.Iter().
Enumerate().
Collect()
ps.Print()
Output: MapOrd{0:aaa, 1:bbb, 2:ccc, 3:ddd, 4:xxx}
func (SeqHeap[V]) Exclude ¶ added in v1.0.181
Exclude returns a new iterator excluding elements that satisfy the provided function.
The function applies the provided function to each element of the iterator. If the function returns true for an element, that element is excluded from the resulting iterator.
Parameters:
- fn (func(V) bool): The function to be applied to each element of the iterator to determine if it should be excluded from the result.
Returns:
- SeqHeap[V]: A new iterator containing the elements that do not satisfy the given condition.
Example usage:
heap := g.NewHeap(cmp.Cmp[int])
heap.Push(1, 2, 3, 4, 5)
notEven := heap.Iter().
Exclude(
func(val int) bool {
return val%2 == 0
}).
Collect(cmp.Cmp[int])
The resulting iterator will contain only the elements that do not satisfy the provided function.
func (SeqHeap[V]) Filter ¶ added in v1.0.181
Filter returns a new iterator containing only the elements that satisfy the provided function.
The function applies the provided function to each element of the iterator. If the function returns true for an element, that element is included in the resulting iterator.
Parameters:
- fn (func(V) bool): The function to be applied to each element of the iterator to determine if it should be included in the result.
Returns:
- SeqHeap[V]: A new iterator containing the elements that satisfy the given condition.
Example usage:
heap := g.NewHeap(cmp.Cmp[int])
heap.Push(1, 2, 3, 4, 5)
even := heap.Iter().
Filter(
func(val int) bool {
return val%2 == 0
}).
Collect(cmp.Cmp[int])
The resulting iterator will contain only the elements that satisfy the provided function.
func (SeqHeap[V]) FilterMap ¶ added in v1.0.184
FilterMap applies a function to each element and filters out None results.
The function transforms and filters elements in a single pass. Elements where the function returns None are filtered out, and elements where it returns Some are unwrapped and included in the result.
Params:
- fn (func(V) Option[V]): The function that transforms and filters elements. Returns Some(value) to include the transformed element, or None to filter it out.
Returns:
- SeqHeap[V]: A sequence containing only the successfully transformed elements.
Example usage:
heap := g.NewHeap(cmp.Cmp[int])
heap.Push(1, 2, 3, 4, 5)
result := heap.Iter().FilterMap(func(n int) g.Option[int] {
if n%2 == 0 {
return g.Some(n * 10)
}
return g.None[int]()
}).Collect(cmp.Cmp[int])
// result contains only even numbers multiplied by 10
func (SeqHeap[V]) Find ¶ added in v1.0.181
Find searches for an element in the iterator that satisfies the provided function.
The function iterates through the elements of the iterator and returns the first element for which the provided function returns true.
Params:
- fn (func(V) bool): The function used to test elements for a condition.
Returns:
- Option[V]: An Option containing the first element that satisfies the condition; None if not found.
Example usage:
heap := g.NewHeap(cmp.Cmp[int])
heap.Push(1, 2, 3, 4, 5)
found := heap.Iter().Find(
func(i int) bool {
return i == 2
})
if found.IsSome() {
fmt.Println("Found:", found.Some())
} else {
fmt.Println("Not found.")
}
The resulting Option may contain the first element that satisfies the condition, or None if not found.
func (SeqHeap[V]) FindMap ¶ added in v1.0.228
FindMap applies fn to each element and returns the first Some result, or None if fn returns None for every element.
func (SeqHeap[V]) FlatMap ¶ added in v1.0.184
FlatMap applies a function to each element and flattens the results into a single sequence.
The function transforms each element into a new SeqHeap and then flattens all resulting sequences into a single sequence.
Params:
- fn (func(V) SeqHeap[V]): The function that transforms each element into a SeqHeap.
Returns:
- SeqHeap[V]: A flattened sequence containing all elements from the transformed sequences.
Example usage:
heap := g.NewHeap(cmp.Cmp[int])
heap.Push(1, 2, 3)
result := heap.Iter().FlatMap(func(n int) g.SeqHeap[int] {
subHeap := g.NewHeap(cmp.Cmp[int])
subHeap.Push(n, n*10)
return subHeap.Iter()
}).Collect(cmp.Cmp[int])
// result contains: 1, 10, 2, 20, 3, 30 (order depends on heap implementation)
func (SeqHeap[V]) Flatten ¶ added in v1.0.181
Flatten flattens an iterator of iterators into a single iterator.
The function creates a new iterator that flattens a sequence of iterators, returning a single iterator containing elements from each iterator in sequence.
Returns:
- SeqHeap[V]: A single iterator containing elements from the sequence of iterators.
Example usage:
heap := g.NewHeap(cmp.Cmp[any])
heap.Push(
1,
g.SliceOf(2, 3),
"abc",
g.SliceOf("def", "ghi"),
g.SliceOf(4.5, 6.7),
)
heap.Iter().Flatten().ForEach(func(v any) { fmt.Print(v, " ") })
Output: 1 2 3 abc def ghi 4.5 6.7
The resulting iterator will contain elements from each iterator in sequence.
func (SeqHeap[V]) Fold ¶ added in v1.0.181
Fold accumulates values in the iterator using a function.
The function iterates through the elements of the iterator, accumulating values using the provided function and an initial value.
Params:
- init (V): The initial value for accumulation.
- fn (func(V, V) V): The function that accumulates values; it takes two arguments of type V and returns a value of type V.
Returns:
- T: The accumulated value after applying the function to all elements.
Example usage:
heap := g.NewHeap(cmp.Cmp[int])
heap.Push(1, 2, 3, 4, 5)
sum := heap.Iter().
Fold(0,
func(acc, val int) int {
return acc + val
})
fmt.Println(sum)
Output: 15.
The resulting value will be the accumulation of elements based on the provided function.
func (SeqHeap[V]) ForEach ¶ added in v1.0.181
func (seq SeqHeap[V]) ForEach(fn func(v V))
ForEach iterates through all elements and applies the given function to each.
The function applies the provided function to each element of the iterator.
Params:
- fn (func(V)): The function to apply to each element.
Example usage:
heap := g.NewHeap(cmp.Cmp[int])
heap.Push(1, 2, 3, 4, 5)
heap.Iter().ForEach(func(val int) {
fmt.Println(val) // Replace this with the function logic you need.
})
The provided function will be applied to each element in the iterator.
func (SeqHeap[V]) Inspect ¶ added in v1.0.181
Inspect creates a new iterator that wraps around the current iterator and allows inspecting each element as it passes through.
func (SeqHeap[V]) Intersperse ¶ added in v1.0.181
Intersperse inserts the provided separator between elements of the iterator.
The function creates a new iterator that inserts the given separator between each consecutive pair of elements in the original iterator.
Params:
- sep (V): The separator to intersperse between elements.
Returns:
- SeqHeap[V]: An iterator containing elements with the separator interspersed.
Example usage:
heap := g.NewHeap(cmp.Cmp[string])
heap.Push("Hello", "World", "!")
heap.Iter().
Intersperse(" ").
ForEach(func(s string) { fmt.Print(s) })
Output: "! Hello World".
The resulting iterator will contain elements with the separator interspersed.
func (SeqHeap[V]) Map ¶ added in v1.0.181
Map transforms each element in the iterator using the given function.
The function creates a new iterator by applying the provided function to each element of the original iterator.
Params:
- fn (func(V) V): The function used to transform elements.
Returns:
- SeqHeap[V]: A iterator containing elements transformed by the provided function.
Example usage:
heap := g.NewHeap(cmp.Cmp[int])
heap.Push(1, 2, 3)
doubled := heap.
Iter().
Map(
func(val int) int {
return val * 2
}).
Collect(cmp.Cmp[int])
The resulting iterator will contain elements transformed by the provided function.
func (SeqHeap[V]) MaxBy ¶ added in v1.0.181
MaxBy returns the maximum element in the sequence using the provided comparison function.
func (SeqHeap[V]) MinBy ¶ added in v1.0.181
MinBy returns the minimum element in the sequence using the provided comparison function.
func (*SeqHeap[V]) Next ¶ added in v1.0.189
Next extracts the next element from the iterator and advances it.
This method consumes the next element from the iterator and returns it wrapped in an Option. The iterator itself is modified to point to the remaining elements.
Returns: - Option[V]: Some(value) if an element exists, None if the iterator is exhausted.
func (SeqHeap[V]) Partition ¶ added in v1.0.181
func (seq SeqHeap[V]) Partition(fn func(v V) bool, leftCmp, rightCmp func(V, V) cmp.Ordering) (*Heap[V], *Heap[V])
Partition divides the elements of the iterator into two separate heaps with custom comparison functions. The comparator arguments are required for the same reason as in Collect: SeqHeap does not carry the source heap's comparator through adapters.
func (SeqHeap[V]) Permutations ¶ added in v1.0.181
Permutations generates iterators of all permutations of elements.
The function uses a recursive approach to generate all the permutations of the elements. If the iterator is empty or contains a single element, it returns the iterator itself wrapped in a single-element iterator.
Returns:
- SeqSlices[V]: An iterator of iterators containing all possible permutations of the elements in the iterator.
Example usage:
heap := g.NewHeap(cmp.Cmp[int])
heap.Push(1, 2, 3)
perms := heap.Iter().Permutations().Collect()
for _, perm := range perms {
fmt.Println(perm)
}
Output: Slice[1, 2, 3] Slice[2, 1, 3] Slice[3, 1, 2] Slice[1, 3, 2] Slice[2, 3, 1] Slice[3, 2, 1]
The resulting iterator will contain iterators representing all possible permutations of the elements in the original iterator.
func (SeqHeap[V]) ProductBy ¶ added in v1.0.228
func (seq SeqHeap[V]) ProductBy[S constraints.Number](fn func(V) S) S
ProductBy maps each element to a numeric value via fn and returns their product. An empty sequence yields the multiplicative identity, one.
func (SeqHeap[V]) Pull ¶ added in v1.0.181
Pull converts the "push-style" iterator sequence seq into a "pull-style" iterator accessed by the two functions next and stop.
Next returns the next value in the sequence and a boolean indicating whether the value is valid. When the sequence is over, next returns the zero V and false. It is valid to call next after reaching the end of the sequence or after calling stop. These calls will continue to return the zero V and false.
Stop ends the iteration. It must be called when the caller is no longer interested in next values and next has not yet signaled that the sequence is over (with a false boolean return). It is valid to call stop multiple times and when next has already returned false.
It is an error to call next or stop from multiple goroutines simultaneously.
func (SeqHeap[V]) Range ¶ added in v1.0.181
Range iterates through elements until the given function returns false.
The function iterates through the elements of the iterator and applies the provided function to each element. It stops iteration when the function returns false for an element.
Params:
- fn (func(V) bool): The function that evaluates elements for continuation of iteration.
Example usage:
heap := g.NewHeap(cmp.Cmp[int])
heap.Push(1, 2, 3, 4, 5)
heap.Iter().Range(func(val int) bool {
fmt.Println(val) // Replace this with the function logic you need.
return val < 5 // Replace this with the condition for continuing iteration.
})
The iteration will stop when the provided function returns false for an element.
func (SeqHeap[V]) Reduce ¶ added in v1.0.181
Reduce aggregates elements of the sequence using the provided function. The first element of the sequence is used as the initial accumulator value. If the sequence is empty, it returns None[V].
Params:
- fn (func(V, V) V): Function that combines two values into one.
Returns:
- Option[V]: The accumulated value wrapped in Some, or None if the sequence is empty.
Example:
heap := g.NewHeap(cmp.Cmp[int])
heap.Push(1, 2, 3, 4, 5)
product := heap.Iter().Reduce(func(a, b int) int { return a * b })
if product.IsSome() {
fmt.Println(product.Some()) // 120
} else {
fmt.Println("empty")
}
func (SeqHeap[V]) Scan ¶ added in v1.0.184
Scan applies a function to each element and produces a sequence of successive accumulated results.
The function takes an initial value and applies the provided function to each element along with the accumulated value, producing a new sequence where each element is the result of the accumulation. The initial value is included as the first element.
Params:
- init (V): The initial value for the accumulation.
- fn (func(acc, val V) V): The function that combines the accumulator with each element.
Returns:
- SeqHeap[V]: A sequence containing the initial value and all accumulated results.
Example usage:
heap := g.NewHeap(cmp.Cmp[int])
heap.Push(1, 2, 3, 4, 5)
result := heap.Iter().Scan(0, func(acc, val int) int {
return acc + val
}).Collect(cmp.Cmp[int])
// result contains: 0, plus cumulative sums of heap elements
func (SeqHeap[V]) Skip ¶ added in v1.0.181
Skip returns a new iterator skipping the first n elements.
The function creates a new iterator that skips the first n elements of the current iterator and returns an iterator starting from the (n+1)th element.
Params:
- n (uint): The number of elements to skip from the beginning of the iterator.
Returns:
- SeqHeap[V]: An iterator that starts after skipping the first n elements.
Example usage:
heap := g.NewHeap(cmp.Cmp[int])
heap.Push(1, 2, 3, 4, 5, 6)
heap.Iter().Skip(3).ForEach(func(v int) { fmt.Print(v, " ") })
Output: 4 5 6
The resulting iterator will start after skipping the specified number of elements.
func (SeqHeap[V]) SkipWhile ¶ added in v1.0.228
SkipWhile skips elements while the predicate returns true, then yields the rest.
func (SeqHeap[V]) SortBy ¶ added in v1.0.181
SortBy applies a custom sorting function to the elements in the iterator and returns a new iterator containing the sorted elements.
The sorting function 'fn' should take two arguments, 'a' and 'b' of type V, and return the ordering between them.
Example:
heap := g.NewHeap(cmp.Cmp[string])
heap.Push("a", "c", "b")
heap.Iter().
SortBy(func(a, b string) cmp.Ordering { return cmp.Cmp(b, a) }).
ForEach(func(s string) { fmt.Print(s, " ") })
Output: c b a
The returned iterator is of type SeqHeap[V], which implements the iterator interface for further iteration over the sorted elements.
func (SeqHeap[V]) StepBy ¶ added in v1.0.181
StepBy creates a new iterator that iterates over every N-th element of the original iterator. This function is useful when you want to skip a specific number of elements between each iteration.
Parameters: - n uint: The step size, indicating how many elements to skip between each iteration.
Returns: - SeqHeap[V]: A new iterator that produces elements from the original iterator with a step size of N.
Example usage:
heap := g.NewHeap(cmp.Cmp[int])
heap.Push(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
heap.Iter().StepBy(3).ForEach(func(v int) { fmt.Print(v, " ") })
Output: 1 4 7 10
The resulting iterator will produce elements from the original iterator with a step size of N.
func (SeqHeap[V]) SumBy ¶ added in v1.0.228
func (seq SeqHeap[V]) SumBy[S constraints.Number](fn func(V) S) S
SumBy maps each element to a numeric value via fn and returns the sum of those values. An empty sequence yields the zero value of S.
func (SeqHeap[V]) Take ¶ added in v1.0.181
Take returns a new iterator with the first n elements. The function creates a new iterator containing the first n elements from the original iterator.
func (SeqHeap[V]) TakeWhile ¶ added in v1.0.228
TakeWhile yields elements while the predicate returns true, stopping at the first false.
func (SeqHeap[V]) TryMap ¶ added in v1.0.228
TryMap applies a fallible transform to each element and enters the Result pipeline, producing a SeqResult[U]. See SeqSlice.TryMap for the full contract.
func (SeqHeap[V]) Unique ¶ added in v1.0.181
Unique returns an iterator with only unique elements.
The function returns an iterator containing only the unique elements from the original iterator.
Returns:
- SeqHeap[V]: An iterator containing unique elements from the original iterator.
Example usage:
heap := g.NewHeap(cmp.Cmp[int])
heap.Push(1, 2, 3, 2, 4, 5, 3)
heap.Iter().Unique().ForEach(func(v int) { fmt.Print(v, " ") })
Output: 1 2 3 4 5
The resulting iterator will contain only unique elements from the original iterator.
func (SeqHeap[V]) Windows ¶ added in v1.0.181
Windows returns an iterator that yields sliding windows of elements of the specified size.
The function creates a new iterator that yields windows of elements from the original iterator, where each window is a slice containing elements of the specified size and moves one element at a time.
Params:
- n (int): The size of each window.
Returns:
- SeqSlices[V]: An iterator yielding sliding windows of elements of the specified size.
Example usage:
heap := g.NewHeap(cmp.Cmp[int]) heap.Push(1, 2, 3, 4, 5, 6) windows := heap.Iter().Windows(3).Collect()
Output: [Slice[1, 2, 3] Slice[2, 3, 4] Slice[3, 4, 5] Slice[4, 5, 6]]
The resulting iterator will yield sliding windows of elements, each containing the specified number of elements.
type SeqMap ¶ added in v1.0.63
type SeqMap[K comparable, V any] iter.Seq2[K, V]
SeqMap is an iterator over sequences of pairs of values, most commonly key-value pairs.
func (SeqMap[K, V]) All ¶ added in v1.0.228
All checks whether all key-value pairs in the iterator satisfy the provided condition. This function is useful when you want to determine if all pairs in an iterator meet a specific criteria.
Parameters: - fn (func(K, V) bool): A function that returns a boolean indicating whether the pair satisfies the condition.
Returns: - bool: True if all pairs in the iterator satisfy the condition, false otherwise.
Example usage:
m := g.Map[string, int]{"a": 1, "b": 2, "c": 3}
allPositive := m.Iter().All(func(_ string, v int) bool { return v > 0 })
The resulting allPositive will be true if all values returned by the iterator are positive.
func (SeqMap[K, V]) Any ¶ added in v1.0.228
Any checks whether any key-value pair in the iterator satisfies the provided condition. This function is useful when you want to determine if at least one pair in an iterator meets a specific criteria.
Parameters: - fn (func(K, V) bool): A function that returns a boolean indicating whether the pair satisfies the condition.
Returns: - bool: True if at least one pair in the iterator satisfies the condition, false otherwise.
Example usage:
m := g.Map[string, int]{"a": 1, "b": 2, "c": 3}
anyEven := m.Iter().Any(func(_ string, v int) bool { return v%2 == 0 })
The resulting anyEven will be true if at least one value returned by the iterator is even.
func (SeqMap[K, V]) Chain ¶ added in v1.0.63
Chain creates a new iterator by concatenating the current iterator with other iterators.
The function concatenates the key-value pairs from the current iterator with the key-value pairs from the provided iterators, producing a new iterator containing all concatenated elements.
Params:
- seqs ([]SeqMap[K, V]): Other iterators to be concatenated with the current iterator.
Returns:
- SeqMap[K, V]: A new iterator containing elements from the current iterator and the provided iterators.
Example usage:
m1 := g.NewMap[int, string]() m1.Insert(1, "a") m2 := g.NewMap[int, string]() m2.Insert(2, "b") // Concatenating iterators and collecting the result. m1.Iter().Chain(m2.Iter()).Collect().Print()
Output: Map{1:a, 2:b} // The output order may vary as Map is not ordered.
The resulting iterator will contain elements from both iterators.
func (SeqMap[K, V]) Chan ¶ added in v1.0.228
Chan converts the sequence into a channel of Pair values, optionally bounded by a context.
func (SeqMap[K, V]) Collect ¶ added in v1.0.63
Collect collects all key-value pairs from the iterator and returns a Map.
func (SeqMap[K, V]) Context ¶ added in v1.0.181
Context allows the iteration to be controlled with a context.Context.
func (SeqMap[K, V]) Count ¶ added in v1.0.63
Count consumes the iterator, counting the number of iterations and returning it.
func (SeqMap[K, V]) Exclude ¶ added in v1.0.63
Exclude returns a new iterator excluding elements that satisfy the provided function.
This function creates a new iterator excluding key-value pairs for which the provided function returns true. It iterates through the current iterator, applying the function to each key-value pair. If the function returns true for a key-value pair, it will be excluded from the resulting iterator.
Params:
- fn (func(K, V) bool): The function applied to each key-value pair to determine exclusion.
Returns:
- SeqMap[K, V]: An iterator excluding elements that satisfy the given function.
Example usage:
m := g.NewMap[int, int]()
m.Insert(1, 1)
m.Insert(2, 2)
m.Insert(3, 3)
m.Insert(4, 4)
m.Insert(5, 5)
notEven := m.Iter().
Exclude(
func(k, v int) bool {
return v%2 == 0
}).
Collect()
notEven.Print()
Output: Map{1:1, 3:3, 5:5} // The output order may vary as Map is not ordered.
The resulting iterator will exclude elements for which the function returns true.
func (SeqMap[K, V]) Filter ¶ added in v1.0.63
Filter returns a new iterator containing only the elements that satisfy the provided function.
This function creates a new iterator containing key-value pairs for which the provided function returns true. It iterates through the current iterator, applying the function to each key-value pair. If the function returns true for a key-value pair, it will be included in the resulting iterator.
Params:
- fn (func(K, V) bool): The function applied to each key-value pair to determine inclusion.
Returns:
- SeqMap[K, V]: An iterator containing elements that satisfy the given function.
m := g.NewMap[int, int]()
m.Insert(1, 1)
m.Insert(2, 2)
m.Insert(3, 3)
m.Insert(4, 4)
m.Insert(5, 5)
even := m.Iter().
Filter(
func(k, v int) bool {
return v%2 == 0
}).
Collect()
even.Print()
Output: Map{2:2, 4:4} // The output order may vary as Map is not ordered.
The resulting iterator will contain elements for which the function returns true.
func (SeqMap[K, V]) FilterByKey ¶ added in v1.0.228
FilterByKey returns a new iterator lazily yielding only the pairs whose key satisfies the provided predicate; values are not inspected.
It lifts a single-parameter predicate to the pair-wise Filter — composes with f.* factories:
m.Iter().FilterByKey(f.Eq("host"))
func (SeqMap[K, V]) FilterByValue ¶ added in v1.0.228
FilterByValue returns a new iterator lazily yielding only the pairs whose value satisfies the provided predicate; keys are not inspected.
It lifts a single-parameter predicate to the pair-wise Filter — composes with f.* factories:
m.Iter().FilterByValue(f.Gt(10))
func (SeqMap[K, V]) FilterMap ¶ added in v1.0.184
func (seq SeqMap[K, V]) FilterMap[K2 comparable, V2 any](fn func(K, V) Option[Pair[K2, V2]]) SeqMap[K2, V2]
FilterMap applies a function to each key-value pair and filters out None results.
The function transforms and filters pairs in a single pass. Pairs where the function returns None are filtered out, and pairs where it returns Some are unwrapped and included in the result.
Params:
- fn (func(K, V) Option[Pair[K, V]]): The function that transforms and filters pairs. Returns Some(Pair{key, value}) to include the transformed pair, or None to filter it out.
Returns:
- SeqMap[K, V]: A sequence containing only the successfully transformed pairs.
Example usage:
configs := g.Map[string, string]{"host": "localhost", "port": "8080", "debug": "invalid"}
validConfigs := configs.Iter().FilterMap(func(k string, v string) Option[Pair[string, string]] {
if k == "port" || k == "host" {
return Some(Pair[string, string]{Key: k, Value: v + "_validated"})
}
return None[Pair[string, string]]()
})
// validConfigs will yield: {"host": "localhost_validated", "port": "8080_validated"}
users := g.Map[string, int]{"alice": 25, "bob": 17, "charlie": 30}
adults := users.Iter().FilterMap(func(name string, age int) Option[Pair[string, int]] {
if age >= 18 {
return Some(Pair[string, int]{Key: name, Value: age})
}
return None[Pair[string, int]]()
})
// adults will yield: {"alice": 25, "charlie": 30}
func (SeqMap[K, V]) Find ¶ added in v1.0.63
Find searches for an element in the iterator that satisfies the provided function.
The function iterates through the elements of the iterator and returns the first element for which the provided function returns true.
Params:
- fn (func(K, V) bool): The function used to test elements for a condition.
Returns:
- Option[K, V]: An Option containing the first element that satisfies the condition; None if not found.
Example usage:
m := g.NewMap[int, int]()
m.Insert(1, 1)
f := m.Iter().Find(func(_ int, v int) bool { return v == 1 })
if f.IsSome() {
print(f.Some().Key)
}
The resulting Option may contain the first element that satisfies the condition, or None if not found.
func (SeqMap[K, V]) FindMap ¶ added in v1.0.228
FindMap applies fn to each key-value pair and returns the first Some result, or None if fn returns None for every pair. Iteration order is undefined.
func (SeqMap[K, V]) First ¶ added in v1.0.225
First returns the first key-value pair from the sequence.
func (SeqMap[K, V]) Fold ¶ added in v1.0.228
Fold reduces the sequence of key-value pairs to a single value using an accumulator. The accumulator type may differ from the key and value types.
func (SeqMap[K, V]) ForEach ¶ added in v1.0.63
func (seq SeqMap[K, V]) ForEach(fn func(k K, v V))
ForEach iterates through all elements and applies the given function to each key-value pair.
This function traverses the entire iterator and applies the provided function to each key-value pair. It iterates through the current iterator, executing the function on each key-value pair.
Params:
- fn (func(K, V)): The function to be applied to each key-value pair in the iterator.
Example usage:
m := g.NewMap[int, int]()
m.Insert(1, 1)
m.Insert(2, 2)
m.Insert(3, 3)
m.Insert(4, 4)
m.Insert(5, 5)
mmap := m.Iter().
Map(
func(k, v int) (int, int) {
return k * k, v * v
}).
Collect()
mmap.Print()
Output: Map{1:1, 4:4, 9:9, 16:16, 25:25} // The output order may vary as Map is not ordered.
The function fn will be executed for each key-value pair in the iterator.
func (SeqMap[K, V]) Inspect ¶ added in v1.0.63
Inspect creates a new iterator that wraps around the current iterator and allows inspecting each key-value pair as it passes through.
func (SeqMap[K, V]) Keys ¶ added in v1.0.63
Keys returns an iterator containing all the keys in the ordered Map.
func (SeqMap[K, V]) Last ¶ added in v1.0.228
Last returns the final key-value pair of the sequence, or None if it is empty. Note: for an unordered Map the notion of "last" depends on iteration order.
func (SeqMap[K, V]) Map ¶ added in v1.0.63
func (seq SeqMap[K, V]) Map[K2 comparable, V2 any](transform func(K, V) (K2, V2)) SeqMap[K2, V2]
Map creates a new iterator by applying the given function to each key-value pair.
This function generates a new iterator by traversing the current iterator and applying the provided function to each key-value pair. It transforms the key-value pairs according to the given function.
Params:
- fn (func(K, V) (K, V)): The function to be applied to each key-value pair in the iterator. It takes a key-value pair and returns a new transformed key-value pair.
Returns:
- SeqMap[K, V]: A new iterator containing key-value pairs transformed by the provided function.
Example usage:
m := g.NewMap[int, int]()
m.Insert(1, 1)
m.Insert(2, 2)
m.Insert(3, 3)
m.Insert(4, 4)
m.Insert(5, 5)
mmap := m.Iter().
Map(
func(k, v int) (int, int) {
return k * k, v * v
}).
Collect()
mmap.Print()
Output: Map{1:1, 4:4, 9:9, 16:16, 25:25} // The output order may vary as Map is not ordered.
The resulting iterator will contain key-value pairs transformed by the given function.
func (*SeqMap[K, V]) Next ¶ added in v1.0.189
Next extracts the next key-value pair from the iterator and advances it.
This method consumes the next key-value pair from the iterator and returns them wrapped in an Option. The iterator itself is modified to point to the remaining elements.
Returns: - Option[Pair[K, V]]: Some(Pair{Key, Value}) if a pair exists, None if the iterator is exhausted.
func (SeqMap[K, V]) Nth ¶ added in v1.0.181
Nth returns the nth key-value pair (0-indexed) in the sequence.
func (SeqMap[K, V]) ProductBy ¶ added in v1.0.228
func (seq SeqMap[K, V]) ProductBy[S constraints.Number](fn func(K, V) S) S
ProductBy maps each key-value pair to a numeric value via fn and returns their product. An empty sequence yields the multiplicative identity, one.
func (SeqMap[K, V]) Pull ¶ added in v1.0.63
Pull converts the “push-style” iterator sequence seq into a “pull-style” iterator accessed by the two functions next and stop.
Next returns the next pair in the sequence and a boolean indicating whether the pair is valid. When the sequence is over, next returns a pair of zero values and false. It is valid to call next after reaching the end of the sequence or after calling stop. These calls will continue to return a pair of zero values and false.
Stop ends the iteration. It must be called when the caller is no longer interested in next values and next has not yet signaled that the sequence is over (with a false boolean return). It is valid to call stop multiple times and when next has already returned false.
It is an error to call next or stop from multiple goroutines simultaneously.
func (SeqMap[K, V]) Range ¶ added in v1.0.63
The iteration will stop when the provided function returns false for an element.
func (SeqMap[K, V]) Skip ¶ added in v1.0.225
Skip returns a new iterator skipping the first n elements.
The function creates a new iterator that skips the first n elements of the current iterator and returns an iterator starting from the (n+1)th element.
Params:
- n (uint): The number of elements to skip from the beginning of the iterator.
Returns:
- SeqMap[K, V]: An iterator that starts after skipping the first n elements.
Example usage:
m := g.NewMap[int, string]() m.Insert(1, "a") m.Insert(2, "b") m.Insert(3, "c") m.Insert(4, "d") // Skipping the first two elements and collecting the rest. m.Iter().Skip(2).Collect().Print()
The resulting iterator will start after skipping the specified number of elements.
func (SeqMap[K, V]) SkipWhile ¶ added in v1.0.228
SkipWhile skips key-value pairs while the predicate returns true, then yields the rest.
func (SeqMap[K, V]) StepBy ¶ added in v1.0.225
StepBy creates a new iterator that iterates over every N-th element of the original iterator. This function is useful when you want to skip a specific number of elements between each iteration.
Parameters: - n uint: The step size, indicating how many elements to skip between each iteration.
Returns: - SeqMap[K, V]: A new iterator that produces key-value pairs from the original iterator with a step size of N.
Example usage:
m := g.NewMap[string, int]()
m.Insert("one", 1)
m.Insert("two", 2)
m.Insert("three", 3)
m.Iter().StepBy(2).Collect().Print()
The resulting iterator will produce key-value pairs from the original iterator with a step size of N.
func (SeqMap[K, V]) SumBy ¶ added in v1.0.228
func (seq SeqMap[K, V]) SumBy[S constraints.Number](fn func(K, V) S) S
SumBy maps each key-value pair to a numeric value via fn and returns the sum of those values. The fold order is undefined, so fn should be free of order-dependent side effects. An empty sequence yields the zero value of S.
func (SeqMap[K, V]) Take ¶ added in v1.0.63
Take returns a new iterator with the first n elements. The function creates a new iterator containing the first n elements from the original iterator.
Values of n larger than math.MaxInt are clamped to math.MaxInt so the conversion to int never wraps to a negative value (which would otherwise cause Take2 to yield nothing).
func (SeqMap[K, V]) TakeWhile ¶ added in v1.0.228
TakeWhile yields key-value pairs while the predicate returns true, stopping at the first false.
type SeqMapOrd ¶ added in v1.0.63
type SeqMapOrd[K comparable, V any] iter.Seq2[K, V]
SeqMapOrd is an iterator over sequences of ordered pairs of values, most commonly ordered key-value pairs.
func (SeqMapOrd[K, V]) All ¶ added in v1.0.228
All checks whether all key-value pairs in the iterator satisfy the provided condition. This function is useful when you want to determine if all pairs in an iterator meet a specific criteria.
Parameters: - fn (func(K, V) bool): A function that returns a boolean indicating whether the pair satisfies the condition.
Returns: - bool: True if all pairs in the iterator satisfy the condition, false otherwise.
Example usage:
m := g.NewMapOrd[g.String, g.Int]()
m.Insert("a", 1)
m.Insert("b", 2)
allPositive := m.Iter().All(func(_ g.String, v g.Int) bool { return v > 0 })
The resulting allPositive will be true if all values returned by the iterator are positive.
func (SeqMapOrd[K, V]) Any ¶ added in v1.0.228
Any checks whether any key-value pair in the iterator satisfies the provided condition. This function is useful when you want to determine if at least one pair in an iterator meets a specific criteria.
Parameters: - fn (func(K, V) bool): A function that returns a boolean indicating whether the pair satisfies the condition.
Returns: - bool: True if at least one pair in the iterator satisfies the condition, false otherwise.
Example usage:
m := g.NewMapOrd[g.String, g.Int]()
m.Insert("a", 1)
m.Insert("b", 2)
anyEven := m.Iter().Any(func(_ g.String, v g.Int) bool { return v%2 == 0 })
The resulting anyEven will be true if at least one value returned by the iterator is even.
func (SeqMapOrd[K, V]) Chain ¶ added in v1.0.63
Chain concatenates the current iterator with other iterators, returning a new iterator.
The function creates a new iterator that combines the elements of the current iterator with elements from the provided iterators in the order they are given.
Params:
- seqs ([]seqMapOrd[K, V]): Other iterators to be concatenated with the current iterator.
Returns:
- SeqMapOrd[K, V]: A new iterator containing elements from the current iterator and the provided iterators.
Example usage:
m1 := g.NewMapOrd[int, string]() m1.Insert(1, "a") m2 := g.NewMapOrd[int, string]() m2.Insert(2, "b") // Concatenating iterators and collecting the result. m1.Iter().Chain(m2.Iter()).Collect().Print()
Output: MapOrd{1:a, 2:b}
The resulting iterator will contain elements from both iterators in the specified order.
func (SeqMapOrd[K, V]) Chan ¶ added in v1.0.205
Chan converts the iterator into a channel, optionally with context(s).
The function converts the key-value pairs from the iterator into a channel, allowing iterative processing using channels. It can be used to stream key-value pairs for concurrent or asynchronous operations.
Params:
- ctxs (...context.Context): Optional context(s) that can be used to cancel or set deadlines for the operation.
Returns:
- chan Pair[K, V]: A channel emitting key-value pairs from the iterator.
Example usage:
m := g.NewMapOrd[int, int]()
m.Insert(1, 1)
m.Insert(2, 2)
m.Insert(3, 3)
m.Insert(4, 4)
m.Insert(5, 5)
ctx, cancel := context.WithCancel(context.Background())
defer cancel() // Ensure cancellation to avoid goroutine leaks.
ch := m.Iter().Chan(ctx)
for pair := range ch {
// Process key-value pair from the channel
}
The function converts the iterator into a channel to allow sequential or concurrent processing of key-value pairs.
func (SeqMapOrd[K, V]) Collect ¶ added in v1.0.63
Collect collects all key-value pairs from the iterator and returns a MapOrd.
Duplicate keys keep their first-seen position, while the value is updated to the most recent one (last-write-wins).
func (SeqMapOrd[K, V]) Context ¶ added in v1.0.181
Context allows the iteration to be controlled with a context.Context.
func (SeqMapOrd[K, V]) Count ¶ added in v1.0.63
Count consumes the iterator, counting the number of iterations and returning it.
func (SeqMapOrd[K, V]) Exclude ¶ added in v1.0.63
Exclude returns a new iterator excluding elements that satisfy the provided function.
The function creates a new iterator excluding elements from the current iterator for which the provided function returns true.
Params:
- fn (func(K, V) bool): The function used to determine exclusion criteria for elements.
Returns:
- SeqMapOrd[K, V]: A new iterator excluding elements that satisfy the given condition.
Example usage:
mo := g.NewMapOrd[int, int]()
mo.Insert(1, 1)
mo.Insert(2, 2)
mo.Insert(3, 3)
mo.Insert(4, 4)
mo.Insert(5, 5)
notEven := mo.Iter().
Exclude(
func(k, v int) bool {
return v%2 == 0
}).
Collect()
notEven.Print()
Output: MapOrd{1:1, 3:3, 5:5}
The resulting iterator will exclude elements based on the provided condition.
func (SeqMapOrd[K, V]) Filter ¶ added in v1.0.63
Filter returns a new iterator containing only the elements that satisfy the provided function.
The function creates a new iterator including elements from the current iterator for which the provided function returns true.
Params:
- fn (func(K, V) bool): The function used to determine inclusion criteria for elements.
Returns:
- SeqMapOrd[K, V]: A new iterator containing elements that satisfy the given condition.
Example usage:
mo := g.NewMapOrd[int, int]()
mo.Insert(1, 1)
mo.Insert(2, 2)
mo.Insert(3, 3)
mo.Insert(4, 4)
mo.Insert(5, 5)
even := mo.Iter().
Filter(
func(k, v int) bool {
return v%2 == 0
}).
Collect()
even.Print()
Output: MapOrd{2:2, 4:4}
The resulting iterator will include elements based on the provided condition.
func (SeqMapOrd[K, V]) FilterByKey ¶ added in v1.0.228
FilterByKey returns a new iterator lazily yielding only the pairs whose key satisfies the provided predicate; values are not inspected.
It lifts a single-parameter predicate to the pair-wise Filter — composes with f.* factories:
mo.Iter().FilterByKey(f.Eq("host"))
func (SeqMapOrd[K, V]) FilterByValue ¶ added in v1.0.228
FilterByValue returns a new iterator lazily yielding only the pairs whose value satisfies the provided predicate; keys are not inspected.
It lifts a single-parameter predicate to the pair-wise Filter — composes with f.* factories:
mo.Iter().FilterByValue(f.Gt(10))
func (SeqMapOrd[K, V]) FilterMap ¶ added in v1.0.228
func (seq SeqMapOrd[K, V]) FilterMap[K2 comparable, V2 any](fn func(K, V) Option[Pair[K2, V2]]) SeqMapOrd[K2, V2]
FilterMap applies a function to each key-value pair and filters out None results.
Pairs where the function returns None are filtered out; pairs where it returns Some(Pair) are transformed and included in the result. Key and value types may differ from the input types.
func (SeqMapOrd[K, V]) Find ¶ added in v1.0.63
Find searches for an element in the iterator that satisfies the provided function.
The function iterates through the elements of the iterator and returns the first element for which the provided function returns true.
Params:
- fn (func(K, V) bool): The function used to test elements for a condition.
Returns:
- Option[K, V]: An Option containing the first element that satisfies the condition; None if not found.
Example usage:
m := g.NewMapOrd[int, int]()
m.Insert(1, 1)
f := m.Iter().Find(func(_ int, v int) bool { return v == 1 })
if f.IsSome() {
print(f.Some().Key)
}
The resulting Option may contain the first element that satisfies the condition, or None if not found.
func (SeqMapOrd[K, V]) FindMap ¶ added in v1.0.228
FindMap applies fn to each key-value pair in insertion order and returns the first Some result, or None if fn returns None for every pair.
func (SeqMapOrd[K, V]) First ¶ added in v1.0.190
First returns the first key-value pair from the sequence.
func (SeqMapOrd[K, V]) Fold ¶ added in v1.0.228
Fold reduces the sequence of key-value pairs to a single value using an accumulator. The accumulator type may differ from the key and value types.
func (SeqMapOrd[K, V]) ForEach ¶ added in v1.0.63
func (seq SeqMapOrd[K, V]) ForEach(fn func(k K, v V))
ForEach iterates through all elements and applies the given function to each key-value pair.
The function applies the provided function to each key-value pair in the iterator.
Params:
- fn (func(K, V)): The function to be applied to each key-value pair in the iterator.
Example usage:
m := g.NewMapOrd[int, int]()
m.Insert(1, 1)
m.Insert(2, 2)
m.Insert(3, 3)
m.Insert(4, 4)
m.Insert(5, 5)
m.Iter().ForEach(func(key K, val V) {
// Process key-value pair
})
The provided function will be applied to each key-value pair in the iterator.
func (SeqMapOrd[K, V]) Inspect ¶ added in v1.0.63
Inspect creates a new iterator that wraps around the current iterator and allows inspecting each key-value pair as it passes through.
func (SeqMapOrd[K, V]) Keys ¶ added in v1.0.63
Keys returns an iterator containing all the keys in the ordered Map.
func (SeqMapOrd[K, V]) Last ¶ added in v1.0.190
Last returns the last key-value pair from the sequence.
func (SeqMapOrd[K, V]) Map ¶ added in v1.0.63
func (seq SeqMapOrd[K, V]) Map[K2 comparable, V2 any](transform func(K, V) (K2, V2)) SeqMapOrd[K2, V2]
Map creates a new iterator by applying the given function to each key-value pair.
The function creates a new iterator by applying the provided function to each key-value pair in the iterator.
Params:
- fn (func(K, V) (K, V)): The function used to transform each key-value pair in the iterator.
Returns:
- SeqMapOrd[K, V]: A new iterator containing transformed key-value pairs.
Example usage:
mo := g.NewMapOrd[int, int]()
mo.Insert(1, 1)
mo.Insert(2, 2)
mo.Insert(3, 3)
mo.Insert(4, 4)
mo.Insert(5, 5)
momap := mo.Iter().
Map(
func(k, v int) (int, int) {
return k * k, v * v
}).
Collect()
momap.Print()
Output: MapOrd{1:1, 4:4, 9:9, 16:16, 25:25}
The resulting iterator will contain transformed key-value pairs.
func (*SeqMapOrd[K, V]) Next ¶ added in v1.0.189
Next extracts the next key-value pair from the iterator and advances it.
This method consumes the next key-value pair from the iterator and returns them wrapped in an Option. The iterator itself is modified to point to the remaining elements.
Returns: - Option[Pair[K, V]]: Some(Pair{Key, Value}) if a pair exists, None if the iterator is exhausted.
func (SeqMapOrd[K, V]) Nth ¶ added in v1.0.181
Nth returns the nth key-value pair (0-indexed) in the sequence.
func (SeqMapOrd[K, V]) ProductBy ¶ added in v1.0.228
func (seq SeqMapOrd[K, V]) ProductBy[S constraints.Number](fn func(K, V) S) S
ProductBy maps each key-value pair to a numeric value via fn and returns their product, in insertion order. An empty sequence yields the multiplicative identity, one.
func (SeqMapOrd[K, V]) Pull ¶ added in v1.0.63
Pull converts the “push-style” iterator sequence seq into a “pull-style” iterator accessed by the two functions next and stop.
Next returns the next pair in the sequence and a boolean indicating whether the pair is valid. When the sequence is over, next returns a pair of zero values and false. It is valid to call next after reaching the end of the sequence or after calling stop. These calls will continue to return a pair of zero values and false.
Stop ends the iteration. It must be called when the caller is no longer interested in next values and next has not yet signaled that the sequence is over (with a false boolean return). It is valid to call stop multiple times and when next has already returned false.
It is an error to call next or stop from multiple goroutines simultaneously.
func (SeqMapOrd[K, V]) Range ¶ added in v1.0.63
Range iterates through elements until the given function returns false.
The function iterates through the key-value pairs in the iterator, applying the provided function to each pair. It continues iterating until the function returns false.
Params:
- fn (func(K, V) bool): The function to be applied to each key-value pair in the iterator.
Example usage:
m := g.NewMapOrd[int, int]()
m.Insert(1, 1)
m.Insert(2, 2)
m.Insert(3, 3)
m.Insert(4, 4)
m.Insert(5, 5)
m.Iter().Range(func(k, v int) bool {
fmt.Println(v) // Replace this with the function logic you need.
return v < 5 // Replace this with the condition for continuing iteration.
})
The iteration will stop when the provided function returns false.
func (SeqMapOrd[K, V]) Skip ¶ added in v1.0.63
m := g.NewMapOrd[int, string]() m.Insert(1, "a") m.Insert(2, "b") m.Insert(3, "c") m.Insert(4, "d") // Skipping the first two elements and collecting the rest. m.Iter().Skip(2).Collect().Print()
Output: MapOrd{3:c, 4:d}
The resulting iterator will start after skipping the specified number of elements.
func (SeqMapOrd[K, V]) SkipWhile ¶ added in v1.0.228
SkipWhile skips key-value pairs while the predicate returns true, then yields the rest.
func (SeqMapOrd[K, V]) SortBy ¶ added in v1.0.63
SortBy applies a custom sorting function to the elements in the iterator and returns a new iterator containing the sorted elements.
The sorting function 'fn' should take two arguments, 'a' and 'b', of type Pair[K, V], and return true if 'a' should be ordered before 'b', and false otherwise.
Example:
m := g.NewMapOrd[g.Int, g.String]()
m.Insert(6, "bb")
m.Insert(0, "dd")
m.Insert(1, "aa")
m.Insert(5, "xx")
m.Insert(2, "cc")
m.Insert(3, "ff")
m.Insert(4, "zz")
m.Iter().
SortBy(
func(a, b g.Pair[g.Int, g.String]) cmp.Ordering {
return a.Key.Cmp(b.Key)
// return a.Value.Cmp(b.Value)
}).
Collect().
Print()
Output: MapOrd{0:dd, 1:aa, 2:cc, 3:ff, 4:zz, 5:xx, 6:bb}
The returned iterator is of type SeqMapOrd[K, V], which implements the iterator interface for further iteration over the sorted elements.
func (SeqMapOrd[K, V]) SortByKey ¶ added in v1.0.73
SortByKey applies a custom sorting function to the keys in the iterator and returns a new iterator containing the sorted elements.
The sorting function 'fn' should take two arguments, 'a' and 'b', of type K, and return true if 'a' should be ordered before 'b', and false otherwise.
Example:
m := g.NewMapOrd[g.Int, g.String]() m.Insert(6, "bb") m.Insert(0, "dd") m.Insert(1, "aa") m.Insert(5, "xx") m.Insert(2, "cc") m.Insert(3, "ff") m.Insert(4, "zz") m.Iter(). SortByKey(g.Int.Cmp). Collect(). Print()
Output: MapOrd{0:dd, 1:aa, 2:cc, 3:ff, 4:zz, 5:xx, 6:bb}
func (SeqMapOrd[K, V]) SortByValue ¶ added in v1.0.73
SortByValue applies a custom sorting function to the values in the iterator and returns a new iterator containing the sorted elements.
The sorting function 'fn' should take two arguments, 'a' and 'b', of type V, and return true if 'a' should be ordered before 'b', and false otherwise.
Example:
m := g.NewMapOrd[g.Int, g.String]() m.Insert(6, "bb") m.Insert(0, "dd") m.Insert(1, "aa") m.Insert(5, "xx") m.Insert(2, "cc") m.Insert(3, "ff") m.Insert(4, "zz") m.Iter(). SortByValue(g.String.Cmp). Collect(). Print()
Output: MapOrd{1:aa, 6:bb, 2:cc, 0:dd, 3:ff, 5:xx, 4:zz}
func (SeqMapOrd[K, V]) StepBy ¶ added in v1.0.63
StepBy creates a new iterator that iterates over every N-th element of the original iterator. This function is useful when you want to skip a specific number of elements between each iteration.
Parameters: - n int: The step size, indicating how many elements to skip between each iteration.
Returns: - SeqMapOrd[K, V]: A new iterator that produces key-value pairs from the original iterator with a step size of N.
Example usage:
mapIter := g.MapOrd[string, int]{{"one", 1}, {"two", 2}, {"three", 3}}.Iter()
iter := mapIter.StepBy(2)
result := iter.Collect()
result.Print()
Output: MapOrd{one:1, three:3}
The resulting iterator will produce key-value pairs from the original iterator with a step size of N.
func (SeqMapOrd[K, V]) SumBy ¶ added in v1.0.228
func (seq SeqMapOrd[K, V]) SumBy[S constraints.Number](fn func(K, V) S) S
SumBy maps each key-value pair to a numeric value via fn and returns the sum of those values, visiting pairs in insertion order. An empty sequence yields the zero value of S.
func (SeqMapOrd[K, V]) Take ¶ added in v1.0.63
Take returns a new iterator with the first n elements. The function creates a new iterator containing the first n elements from the original iterator.
func (SeqMapOrd[K, V]) TakeWhile ¶ added in v1.0.228
TakeWhile yields key-value pairs while the predicate returns true, stopping at the first false.
func (SeqMapOrd[K, V]) TryMap ¶ added in v1.0.228
TryMap applies a fallible transform to each key-value pair and enters the Result pipeline, producing a SeqResult[U]. See SeqSlice.TryMap for the full contract.
type SeqPairs ¶ added in v1.0.228
SeqPairs is a lazy sequence of key-value pairs produced by zipping two sequences. Unlike SeqMapOrd, its first type parameter is not required to be comparable, so it can carry pairs of arbitrary types.
Note: SeqPairs deliberately does not provide methods whose signatures would instantiate generic containers with Pair[K, V] as a type argument (e.g. Collect returning Slice[Pair[K, V]]); such signatures would create an instantiation cycle with the generic Zip methods. Collect therefore returns a plain []Pair[K, V], which callers can convert to a Slice with g.SliceOf(pairs...) at a concrete type.
func (SeqPairs[K, V]) All ¶ added in v1.0.228
All returns true if fn returns true for every pair in the sequence. It stops at the first pair for which fn returns false.
func (SeqPairs[K, V]) Any ¶ added in v1.0.228
Any returns true if fn returns true for at least one pair in the sequence. It stops at the first pair for which fn returns true.
func (SeqPairs[K, V]) Collect ¶ added in v1.0.228
Collect consumes the sequence and returns all pairs as a plain []Pair slice. Convert to a g.Slice at a concrete type with g.SliceOf(pairs...) if chaining is needed.
func (SeqPairs[K, V]) Count ¶ added in v1.0.228
Count consumes the sequence and returns the number of pairs.
func (SeqPairs[K, V]) Exclude ¶ added in v1.0.228
Exclude returns a sequence containing only the pairs for which fn returns false.
func (SeqPairs[K, V]) Filter ¶ added in v1.0.228
Filter returns a sequence containing only the pairs for which fn returns true.
func (SeqPairs[K, V]) FilterByKey ¶ added in v1.0.228
FilterByKey returns a sequence lazily yielding only the pairs whose first element satisfies the provided predicate; second elements are not inspected.
It lifts a single-parameter predicate to the pair-wise Filter — composes with f.* factories:
pairs.FilterByKey(f.Gt(10))
func (SeqPairs[K, V]) FilterByValue ¶ added in v1.0.228
FilterByValue returns a sequence lazily yielding only the pairs whose second element satisfies the provided predicate; first elements are not inspected.
It lifts a single-parameter predicate to the pair-wise Filter — composes with f.* factories:
pairs.FilterByValue(f.Eq("ok"))
func (SeqPairs[K, V]) Find ¶ added in v1.0.228
Find returns the first pair satisfying fn, or None if no pair matches.
func (SeqPairs[K, V]) FindMap ¶ added in v1.0.228
FindMap applies fn to each pair and returns the first Some result, or None if fn returns None for every pair.
func (SeqPairs[K, V]) Fold ¶ added in v1.0.228
Fold reduces the sequence of pairs to a single value using an accumulator. The accumulator type may differ from the key and value types.
func (SeqPairs[K, V]) ForEach ¶ added in v1.0.228
func (seq SeqPairs[K, V]) ForEach(fn func(K, V))
ForEach applies fn to each pair in the sequence.
func (SeqPairs[K, V]) Inspect ¶ added in v1.0.228
Inspect calls fn on each pair as it passes through the sequence, without modifying it.
func (SeqPairs[K, V]) Keys ¶ added in v1.0.228
Keys returns a sequence of the first elements of each pair.
func (SeqPairs[K, V]) Map ¶ added in v1.0.228
Map transforms each pair into a single value using the given function, returning a sequence of the results.
func (SeqPairs[K, V]) ProductBy ¶ added in v1.0.228
func (seq SeqPairs[K, V]) ProductBy[S constraints.Number](fn func(K, V) S) S
ProductBy maps each pair to a numeric value via fn and returns their product. An empty sequence yields the multiplicative identity, one.
func (SeqPairs[K, V]) Skip ¶ added in v1.0.228
Skip returns a sequence that skips the first n pairs.
func (SeqPairs[K, V]) SkipWhile ¶ added in v1.0.228
SkipWhile skips pairs while the predicate returns true, then yields the rest.
func (SeqPairs[K, V]) SumBy ¶ added in v1.0.228
func (seq SeqPairs[K, V]) SumBy[S constraints.Number](fn func(K, V) S) S
SumBy maps each key-value pair to a numeric value via fn and returns the sum of those values. An empty sequence yields the zero value of S.
func (SeqPairs[K, V]) Take ¶ added in v1.0.228
Take returns a sequence containing at most n leading pairs.
func (SeqPairs[K, V]) TakeWhile ¶ added in v1.0.228
TakeWhile yields pairs while the predicate returns true, stopping at the first false.
func (SeqPairs[K, V]) TryMap ¶ added in v1.0.228
TryMap applies a fallible transform to each pair and enters the Result pipeline, producing a SeqResult[U]. See SeqSlice.TryMap for the full contract.
type SeqResult ¶ added in v1.0.115
SeqResult is an iterator over sequences of Result[V] values.
func ErrSeq ¶ added in v1.0.222
ErrSeq wraps a single error into a SeqResult iterator. Useful for early returns in functions that produce a SeqResult, where a plain error needs to be lifted into the sequence type.
Example:
return ErrSeq[int](errors.New("something went wrong"))
func FromResultChan ¶ added in v1.0.209
FromResultChan converts a channel of Results into a SeqResult iterator. It consumes the channel until it's closed, yielding each Result to the iterator. This is particularly useful with pool.Stream() for processing task results as they complete in real-time.
Example usage with pool.Stream:
ch := pool.New[int]().Limit(10).Stream(func() {
for i := range 100 {
p.Go(func() Result[int] {
if i%10 == 0 {
return Err[int](fmt.Errorf("task %d failed", i))
}
return Ok(i * i)
})
}
})
successful, failed := FromResultChan(ch).Partition()
fmt.Printf("Successful: %d, Failed: %d\n", successful.Len(), failed.Len())
func OkSeq ¶ added in v1.0.222
OkSeq wraps a single Ok value into a SeqResult iterator. Useful for returning a successful single-element sequence without manually constructing the yield function.
Example:
return OkSeq(42)
func (SeqResult[V]) All ¶ added in v1.0.115
All checks whether all Ok values in the sequence satisfy the provided condition.
If an Err is encountered in the sequence, that Err is immediately returned. Otherwise, it returns Ok(true) if all Ok values satisfy the function, or Ok(false) if at least one does not.
func (SeqResult[V]) Any ¶ added in v1.0.115
Any checks whether any Ok value in the sequence satisfies the provided condition.
If an Err is encountered, that Err is immediately returned. Otherwise, it returns Ok(true) if at least one Ok value satisfies the function, or Ok(false) if none do.
func (SeqResult[V]) Chain ¶ added in v1.0.115
Chain concatenates this sequence with other sequences, returning a new sequence of Result[V].
The function yields all elements (Ok or Err) from the current sequence, then from each of the provided sequences in order. Err elements are yielded like any other element (consumer-driven).
func (SeqResult[V]) Collect ¶ added in v1.0.115
Collect gathers all elements from the iterator into a Slice of Result values. Both Ok and Err elements are collected as-is; encountering an Err does not stop the collection.
func (SeqResult[V]) Context ¶ added in v1.0.181
Context allows the iteration to be controlled with a context.Context.
func (SeqResult[V]) Count ¶ added in v1.0.116
Count consumes the entire sequence, counting the number of elements it yields. Err elements are counted like Ok elements and do not stop the count.
func (SeqResult[V]) CounterBy ¶ added in v1.0.228
func (seq SeqResult[V]) CounterBy[K comparable](fn func(V) K) Result[MapOrd[K, Int]]
CounterBy counts how many Ok values map to each key produced by fn, returning the tally as a MapOrd in first-seen key order. It is a short-circuit terminal: the first Err stops the count and is returned as Err. (A lazy SeqResult of the tally is impossible here — it would instantiate SeqResult with a type built from V and hit an instantiation cycle.)
func (SeqResult[V]) Dedup ¶ added in v1.0.115
Dedup removes consecutive duplicates of Ok values from the sequence, returning a new sequence.
If an Err is encountered, it is yielded downstream as-is (consumer-driven). Consecutive Ok duplicates (based on equality) are filtered out so only the first occurrence is yielded.
func (SeqResult[V]) Err ¶ added in v1.0.191
Err returns a new sequence containing only the error values from the original sequence. All Ok values are filtered out.
func (SeqResult[V]) Exclude ¶ added in v1.0.115
Exclude returns a new sequence that excludes Ok elements which satisfy the provided function.
If an Err is encountered, it is yielded downstream as-is (consumer-driven). Only Ok elements for which 'fn' returns false are yielded downstream.
func (SeqResult[V]) Filter ¶ added in v1.0.115
Filter returns a new sequence containing only the Ok elements that satisfy the provided function.
If an Err is encountered, it is yielded downstream as-is; the consumer decides whether to continue (consumer-driven). Only Ok elements for which fn returns true are yielded downstream as Ok.
func (SeqResult[V]) FilterMap ¶ added in v1.0.228
FilterMap transforms each Ok value with fn and keeps only the Some results, changing the element type from V to U.
If an Err is encountered, it is passed downstream as-is (Err[U]); the consumer decides whether to continue (consumer-driven). For an Ok value, fn is applied: Some(u) is yielded as Ok(u), None drops the element.
func (SeqResult[V]) Find ¶ added in v1.0.116
Find searches the sequence for the first Ok value that satisfies the provided function.
If an Err is encountered, it returns that Err immediately. If a matching Ok value is found, iteration stops and we return Ok(Some(...)). If no matching Ok value is found, it returns Ok(None).
func (SeqResult[V]) FindMap ¶ added in v1.0.228
FindMap applies fn to each Ok value and returns the first Some result wrapped in Ok; None if fn returns None for every value. The first Err short-circuits and is returned as Err.
func (SeqResult[V]) First ¶ added in v1.0.190
First returns the first Ok element from the sequence. If the sequence is empty or contains only Err values, None is returned. If an Err is encountered, that Err is returned.
func (SeqResult[V]) FirstErr ¶ added in v1.0.191
FirstErr returns the first error encountered in the sequence. If no error is found, it returns None. The iteration stops at the first error.
func (SeqResult[V]) FlatMap ¶ added in v1.0.228
FlatMap transforms each Ok value into a sequence and flattens the results, wrapping each produced element in Ok. The element type may differ from the input type. If an Err is encountered, it is passed downstream as-is; iteration continues for as long as the consumer keeps accepting values (consumer-driven), matching Map.
Example:
seq.FlatMap(Slice[Int].Iter) // SeqResult[Slice[Int]] -> SeqResult[Int]
func (SeqResult[V]) Flatten ¶ added in v1.0.228
Flatten flattens one or more levels of nested slices/arrays inside each Ok value, yielding the leaf elements as Ok. Err elements are passed downstream as-is (consumer-driven). It mirrors SeqSlice.Flatten and, like it, relies on reflection: only leaves assignable to V are yielded.
func (SeqResult[V]) Fold ¶ added in v1.0.228
Fold reduces the sequence to a single value using an accumulator. The accumulator type may differ from the element type. The first Err short-circuits the iteration and is returned as Err.
func (SeqResult[V]) ForEach ¶ added in v1.0.115
ForEach applies a function to each Result in the sequence (Ok or Err) without modifying the sequence.
The iteration continues over all elements, passing them to fn for side effects.
func (SeqResult[V]) Inspect ¶ added in v1.0.115
Inspect calls fn for every Ok value without changing it. Err elements are passed through unchanged (consumer-driven).
func (SeqResult[V]) Intersperse ¶ added in v1.0.115
Intersperse inserts the provided Ok separator between each Ok element of the sequence.
If an Err is encountered, it is yielded as-is without a separator (consumer-driven). For Ok elements, after the first yield, a separator is inserted before each subsequent Ok value.
func (SeqResult[V]) Last ¶ added in v1.0.190
Last returns the last Ok element from the sequence. If the sequence is empty or contains only Err values, None is returned. If an Err is encountered, that Err is returned.
func (SeqResult[V]) Map ¶ added in v1.0.115
Map transforms each Ok value in the sequence using the given function, returning a new sequence of Result. The result type may differ from the input type.
If an Err is encountered, it is passed downstream as-is; iteration continues for as long as the consumer keeps accepting values (consumer-driven).
func (SeqResult[V]) MaxBy ¶ added in v1.0.228
MaxBy returns the maximum Ok value according to fn, mirroring the short-circuit terminals: the first Err stops iteration and is returned as Err; a sequence with no Ok values yields Ok(None).
func (SeqResult[V]) MinBy ¶ added in v1.0.228
MinBy returns the minimum Ok value according to fn, mirroring the short-circuit terminals: the first Err stops iteration and is returned as Err; a sequence with no Ok values yields Ok(None).
func (*SeqResult[V]) Next ¶ added in v1.0.189
Next extracts the next element from the iterator and advances it.
This method consumes the next element from the iterator and returns it wrapped in an Option. The iterator itself is modified to point to the remaining elements.
Returns: - Option[Result[V]]: Some(Result[V]) if an element exists, None if the iterator is exhausted.
func (SeqResult[V]) Nth ¶ added in v1.0.181
Nth returns the nth Ok element (0-indexed) in the sequence. If an Err is encountered before reaching the nth element, that Err is returned. If there are fewer than n+1 Ok elements, None is returned.
func (SeqResult[V]) Ok ¶ added in v1.0.191
Ok returns a new sequence containing only the Ok values from the original sequence. All Err values are filtered out.
func (SeqResult[V]) Partition ¶ added in v1.0.191
Partition separates the sequence into two slices: one containing all Ok values and one containing all errors. The iteration continues through all elements, collecting each into the appropriate slice.
func (SeqResult[V]) ProductBy ¶ added in v1.0.228
func (seq SeqResult[V]) ProductBy[S constraints.Number](fn func(V) S) Result[S]
ProductBy maps each Ok value to a numeric value via fn and returns their product wrapped in Ok. The first Err short-circuits and is returned as Err[S]. An empty (or all-consumed) sequence yields Ok of the multiplicative identity, one.
func (SeqResult[V]) Pull ¶ added in v1.0.115
Pull converts the “push-style” sequence of Result[V] into a “pull-style” iterator accessed by two functions: next and stop.
The next function returns the next Result[V] in the sequence and a boolean indicating whether the value is valid. When the sequence is over, next returns the zero value and false. It is valid to call next after reaching the end of the sequence or after calling stop. These calls will continue to return the zero value and false.
The stop function ends the iteration. It must be called when the caller is no longer interested in next values and next has not yet signaled that the sequence is over. It is valid to call stop multiple times and after next has already returned false.
It is an error to call next or stop from multiple goroutines simultaneously.
func (SeqResult[V]) Range ¶ added in v1.0.115
Range iterates through elements until the given function returns false.
For each element (Ok or Err), fn is called. If fn returns false, iteration stops immediately.
func (SeqResult[V]) Reduce ¶ added in v1.0.228
Reduce aggregates Ok values using the provided function: the first Err short-circuits and is returned as Err; an empty sequence yields Ok(None); otherwise Ok(Some(accumulated)).
func (SeqResult[V]) Scan ¶ added in v1.0.228
Scan accumulates Ok values, yielding the initial value followed by every intermediate accumulator state. The accumulator type may differ from the element type. An Err is passed downstream as-is without touching the accumulator; iteration continues for as long as the consumer keeps accepting values (consumer-driven).
func (SeqResult[V]) Skip ¶ added in v1.0.115
Skip returns a new sequence that skips the first n Ok elements.
If an Err is encountered, it is yielded as-is without consuming the skip budget (consumer-driven). Once n Ok elements have been skipped, subsequent elements (Ok or Err) are yielded normally.
func (SeqResult[V]) SkipWhile ¶ added in v1.0.228
SkipWhile skips Ok values while fn returns true, then yields every remaining element.
If an Err is encountered, it is passed downstream as-is regardless of the skipping phase (consumer-driven); the skipping predicate is evaluated only on Ok values.
func (SeqResult[V]) SortBy ¶ added in v1.0.228
SortBy consumes the sequence, sorts the Ok values with fn, and re-emits them in order as a SeqResult. Being a sort, it is eager: the whole sequence is buffered first. The first Err short-circuits — buffering stops and only that Err is yielded downstream.
func (SeqResult[V]) StepBy ¶ added in v1.0.115
StepBy creates a new sequence that yields every nth Ok element from the original sequence.
If an Err is encountered, it is yielded downstream as-is (consumer-driven). For Ok elements, only every n-th element is yielded.
func (SeqResult[V]) SumBy ¶ added in v1.0.228
func (seq SeqResult[V]) SumBy[S constraints.Number](fn func(V) S) Result[S]
SumBy maps each Ok value to a numeric value via fn and returns their sum wrapped in Ok. The first Err short-circuits: iteration stops and that error is returned as Err[S]. An empty (or all-consumed) sequence yields Ok of the zero value of S.
func (SeqResult[V]) Take ¶ added in v1.0.115
Take returns a new sequence with the first n Ok elements. If an Err is encountered, it is yielded downstream as-is (consumer-driven). After n Ok elements are yielded, the sequence ends.
func (SeqResult[V]) TakeWhile ¶ added in v1.0.228
TakeWhile yields Ok values while fn returns true, stopping at the first Ok value for which fn returns false.
If an Err is encountered, it is passed downstream as-is and does not stop the taking (consumer-driven); only a failing predicate on an Ok value ends it.
func (SeqResult[V]) TryCollect ¶ added in v1.0.228
TryCollect gathers the Ok values from the sequence into a Slice: the first Err short-circuits — iteration stops immediately, elements after it are not consumed — and that error is returned as Err. An empty sequence yields Ok of an empty Slice.
Unlike Collect, which gathers every element (Ok and Err alike) into a Slice[Result[V]], TryCollect returns Result[Slice[V]]: either all the unwrapped Ok values, or the first error encountered.
type SeqSet ¶ added in v1.0.63
type SeqSet[V comparable] iter.Seq[V]
SeqSet is an iterator over sequences of unique values.
func (SeqSet[V]) All ¶ added in v1.0.225
All checks whether all elements in the iterator satisfy the provided condition. This function is useful when you want to determine if all elements in an iterator meet a specific criteria.
Parameters: - fn func(V) bool: A function that returns a boolean indicating whether the element satisfies the condition.
Returns: - bool: True if all elements in the iterator satisfy the condition, false otherwise.
Example usage:
set := g.SetOf(1, 2, 3, 4, 5, 6, 7)
isPositive := func(num int) bool { return num > 0 }
allPositive := set.Iter().All(isPositive)
The resulting allPositive will be true if all elements returned by the iterator are positive.
func (SeqSet[V]) Any ¶ added in v1.0.225
Any checks whether any element in the iterator satisfies the provided condition. This function is useful when you want to determine if at least one element in an iterator meets a specific criteria.
Parameters: - fn func(V) bool: A function that returns a boolean indicating whether the element satisfies the condition.
Returns: - bool: True if at least one element in the iterator satisfies the condition, false otherwise.
Example usage:
set := g.SetOf(1, 3, 5, 7, 9)
isEven := func(num int) bool { return num%2 == 0 }
anyEven := set.Iter().Any(isEven)
The resulting anyEven will be true if at least one element returned by the iterator is even.
func (SeqSet[V]) Chain ¶ added in v1.0.63
Chain concatenates the current iterator with other iterators, returning a new iterator.
The function creates a new iterator that combines the elements of the current iterator with elements from the provided iterators in the order they are given.
Params:
- seqs ([]SeqSet[V]): Other iterators to be concatenated with the current iterator.
Returns:
- SeqSet[V]: A new iterator containing elements from the current iterator and the provided iterators.
Example usage:
iter1 := g.SetOf(1, 2, 3).Iter() iter2 := g.SetOf(4, 5, 6).Iter() iter1.Chain(iter2).Collect().Print()
Output: Set{3, 4, 5, 6, 1, 2} // The output order may vary as the Set type is not ordered.
The resulting iterator will contain elements from both iterators.
func (SeqSet[V]) Chan ¶ added in v1.0.228
Chan converts the iterator into a channel, optionally with context(s).
The function converts the elements of the iterator into a channel for streaming purposes. Optionally, it accepts context(s) to handle cancellation or timeout scenarios.
Params:
- ctxs (context.Context): Optional context(s) to control the channel behavior (e.g., cancellation).
Returns:
- chan V: A channel containing the elements from the iterator.
Example usage:
set := g.SetOf(1, 2, 3)
ctx, cancel := context.WithCancel(context.Background())
defer cancel() // Ensure cancellation to avoid goroutine leaks.
ch := set.Iter().Chan(ctx)
for val := range ch {
fmt.Println(val)
}
The resulting channel allows streaming elements from the iterator with optional context handling.
func (SeqSet[V]) Collect ¶ added in v1.0.63
Collect gathers all elements from the iterator into a Set.
func (SeqSet[V]) Context ¶ added in v1.0.181
Context allows the iteration to be controlled with a context.Context.
func (SeqSet[V]) Count ¶ added in v1.0.63
Count consumes the iterator, counting the number of iterations and returning it.
func (SeqSet[V]) CounterBy ¶ added in v1.0.228
func (seq SeqSet[V]) CounterBy[K comparable](fn func(V) K) SeqMapOrd[K, Int]
CounterBy consumes the sequence and returns an ordered map from fn(element) to the number of elements that produced that key: fn is applied to every element, and elements whose keys collide are merged into one bucket with their counts summed. Key order is first-seen. The key type must be comparable; for identity counting pass the identity function (func(v V) V { return v }).
Example usage:
words.Iter().CounterBy(func(w String) Int { return w.Len() })
// MapOrd{5:2, 4:1} — counts by word length, in first-seen order
func (SeqSet[V]) Difference ¶ added in v1.0.228
Difference returns a sequence containing the elements of the sequence that are not present in the other set.
func (SeqSet[V]) Exclude ¶ added in v1.0.63
Exclude returns a new iterator excluding elements that satisfy the provided function.
The function applies the provided function to each element of the iterator. If the function returns true for an element, that element is excluded from the resulting iterator.
Parameters:
- fn (func(V) bool): The function to be applied to each element of the iterator to determine if it should be excluded from the result.
Returns:
- SeqSet[V]: A new iterator containing the elements that do not satisfy the given condition.
Example usage:
set := g.SetOf(1, 2, 3, 4, 5)
notEven := set.Iter().
Exclude(
func(val int) bool {
return val%2 == 0
}).
Collect()
notEven.Print()
Output: Set{1, 3, 5} // The output order may vary as the Set type is not ordered.
The resulting iterator will contain only the elements that do not satisfy the provided function.
func (SeqSet[V]) Filter ¶ added in v1.0.63
Filter returns a new iterator containing only the elements that satisfy the provided function.
The function applies the provided function to each element of the iterator. If the function returns true for an element, that element is included in the resulting iterator.
Parameters:
- fn (func(V) bool): The function to be applied to each element of the iterator to determine if it should be included in the result.
Returns:
- SeqSet[V]: A new iterator containing the elements that satisfy the given condition.
Example usage:
set := g.SetOf(1, 2, 3, 4, 5)
even := set.Iter().
Filter(
func(val int) bool {
return val%2 == 0
}).
Collect()
even.Print()
Output: Set{2, 4} // The output order may vary as the Set type is not ordered.
The resulting iterator will contain only the elements that satisfy the provided function.
func (SeqSet[V]) FilterMap ¶ added in v1.0.225
func (seq SeqSet[V]) FilterMap[U comparable](fn func(V) Option[U]) SeqSet[U]
FilterMap applies a function to each element and filters out None results.
The function transforms and filters elements in a single pass. Elements where the function returns None are filtered out, and elements where it returns Some are unwrapped and included in the result.
Params:
- fn (func(V) Option[V]): The function that transforms and filters elements. Returns Some(value) to include the transformed value, or None to filter it out.
Returns:
- SeqSet[V]: A sequence containing only the successfully transformed elements.
Example usage:
set := g.SetOf(1, 2, 3, 4, 5)
result := set.Iter().FilterMap(func(n int) g.Option[int] {
if n%2 == 0 {
return g.Some(n * 10)
}
return g.None[int]()
}).Collect()
// result contains only even numbers multiplied by 10
func (SeqSet[V]) Find ¶ added in v1.0.114
Find searches for an element in the iterator that satisfies the provided function.
The function iterates through the elements of the iterator and returns the first element for which the provided function returns true.
Params:
- fn (func(V) bool): The function used to test elements for a condition.
Returns:
- Option[V]: An Option containing the first element that satisfies the condition; None if not found.
Example usage:
iter := g.SetOf(1, 2, 3, 4, 5).Iter()
found := // func(i int) bool {
return i == 2
}.Find()
if found.IsSome() {
fmt.Println("Found:", found.Some())
} else {
fmt.Println("Not found.")
}
The resulting Option may contain the first element that satisfies the condition, or None if not found.
func (SeqSet[V]) FindMap ¶ added in v1.0.228
FindMap applies fn to each element and returns the first Some result, or None if fn returns None for every element. Iteration order over a set is undefined.
func (SeqSet[V]) First ¶ added in v1.0.228
First returns the first element from the sequence. Note: for an unordered Set the notion of "first" depends on iteration order.
func (SeqSet[V]) Fold ¶ added in v1.0.225
Fold accumulates values in the iterator using a function.
The function iterates through the elements of the iterator, accumulating values using the provided function and an initial value.
Params:
- init (V): The initial value for accumulation.
- fn (func(V, V) V): The function that accumulates values; it takes two arguments of type V and returns a value of type V.
Returns:
- V: The accumulated value after applying the function to all elements.
Example usage:
set := g.SetOf(1, 2, 3, 4, 5)
sum := set.Iter().
Fold(0,
func(acc, val int) int {
return acc + val
})
fmt.Println(sum)
Output: 15.
The resulting value will be the accumulation of elements based on the provided function.
func (SeqSet[V]) ForEach ¶ added in v1.0.63
func (seq SeqSet[V]) ForEach(fn func(v V))
ForEach iterates through all elements and applies the given function to each.
The function applies the provided function to each element of the iterator.
Params:
- fn (func(V)): The function to apply to each element.
Example usage:
iter := g.SetOf(1, 2, 3).Iter()
func(val V) {
fmt.Println(val) // Replace this with the function logic you need.
}.ForEach()
The provided function will be applied to each element in the iterator.
func (SeqSet[V]) Inspect ¶ added in v1.0.63
Inspect creates a new iterator that wraps around the current iterator and allows inspecting each element as it passes through.
func (SeqSet[V]) Intersection ¶ added in v1.0.228
Intersection returns a sequence containing only the elements of the sequence that are also present in the other set.
func (SeqSet[V]) Last ¶ added in v1.0.228
Last returns the final element of the sequence, or None if it is empty. Note: for an unordered Set the notion of "last" depends on iteration order.
func (SeqSet[V]) Map ¶ added in v1.0.63
func (seq SeqSet[V]) Map[U comparable](transform func(V) U) SeqSet[U]
Map transforms each element in the iterator using the given function.
The function creates a new iterator by applying the provided function to each element of the original iterator.
Params:
- fn (func(V) U): The function used to transform elements. The result type may differ from the element type but must be comparable.
Returns:
- SeqSet[U]: A new iterator containing elements transformed by the provided function.
Example usage:
set := g.SetOf(1, 2, 3)
doubled := set.Iter().
Map(
func(val int) int {
return val * 2
}).
Collect()
doubled.Print()
Output: Set{2, 4, 6} // The output order may vary as the Set type is not ordered.
The resulting iterator will contain elements transformed by the provided function.
func (SeqSet[V]) MaxBy ¶ added in v1.0.228
MaxBy returns the maximum element in the sequence using the provided comparison function.
func (SeqSet[V]) MinBy ¶ added in v1.0.228
MinBy returns the minimum element in the sequence using the provided comparison function.
func (*SeqSet[V]) Next ¶ added in v1.0.189
Next extracts the next element from the iterator and advances it.
This method consumes the next element from the iterator and returns it wrapped in an Option. The iterator itself is modified to point to the remaining elements.
Returns: - Option[V]: Some(value) if an element exists, None if the iterator is exhausted.
func (SeqSet[V]) Partition ¶ added in v1.0.228
Partition consumes the sequence and splits its elements into two sets based on the predicate: elements for which fn returns true go into the first set, the rest into the second.
func (SeqSet[V]) ProductBy ¶ added in v1.0.228
func (seq SeqSet[V]) ProductBy[S constraints.Number](fn func(V) S) S
ProductBy maps each element to a numeric value via fn and returns their product. An empty sequence yields the multiplicative identity, one.
func (SeqSet[V]) Pull ¶ added in v1.0.63
Pull converts the “push-style” iterator sequence seq into a “pull-style” iterator accessed by the two functions next and stop.
Next returns the next value in the sequence and a boolean indicating whether the value is valid. When the sequence is over, next returns the zero V and false. It is valid to call next after reaching the end of the sequence or after calling stop. These calls will continue to return the zero V and false.
Stop ends the iteration. It must be called when the caller is no longer interested in next values and next has not yet signaled that the sequence is over (with a false boolean return). It is valid to call stop multiple times and when next has already returned false.
It is an error to call next or stop from multiple goroutines simultaneously.
func (SeqSet[V]) Range ¶ added in v1.0.63
Range iterates through elements until the given function returns false.
The function iterates through the elements of the iterator and applies the provided function to each element. The iteration will stop when the provided function returns false for an element.
Params: - fn (func(V) bool): The function that evaluates elements for continuation of iteration.
Example usage:
iter := g.SetOf(1, 2, 2, 3, 4, 5).Iter()
func(v int) bool {
if v == 3 {
return false
}
print(v)
return true
}.Range()
func (SeqSet[V]) Reduce ¶ added in v1.0.225
Reduce aggregates elements of the sequence using the provided function. The first element of the sequence is used as the initial accumulator value. If the sequence is empty, it returns None[V].
Params:
- fn (func(V, V) V): Function that combines two values into one.
Returns:
- Option[V]: The accumulated value wrapped in Some, or None if the sequence is empty.
Example:
set := g.SetOf(1, 2, 3, 4, 5)
product := set.Iter().Reduce(func(a, b int) int { return a * b })
if product.IsSome() {
fmt.Println(product.Some()) // 120
} else {
fmt.Println("empty")
}
func (SeqSet[V]) Skip ¶ added in v1.0.225
Skip returns a new iterator skipping the first n elements.
The function creates a new iterator that skips the first n elements of the current iterator and returns an iterator starting from the (n+1)th element.
Params:
- n (uint): The number of elements to skip from the beginning of the iterator.
Returns:
- SeqSet[V]: An iterator that starts after skipping the first n elements.
Example usage:
set := g.SetOf(1, 2, 3, 4, 5, 6) set.Iter().Skip(3).Collect().Print()
The resulting iterator will start after skipping the specified number of elements.
func (SeqSet[V]) SkipWhile ¶ added in v1.0.228
SkipWhile skips elements while the predicate returns true, then yields the rest.
func (SeqSet[V]) StepBy ¶ added in v1.0.228
StepBy creates a new iterator that iterates over every N-th element of the original iterator. This function is useful when you want to skip a specific number of elements between each iteration. Note: for an unordered Set, which elements are selected depends on iteration order.
Parameters: - n uint: The step size, indicating how many elements to skip between each iteration.
Returns: - SeqSet[V]: A new iterator that produces elements from the original iterator with a step size of N.
Example usage:
set := g.SetOf(1, 2, 3, 4, 5, 6) set.Iter().StepBy(2).Collect().Print()
The resulting iterator will produce elements from the original iterator with a step size of N.
func (SeqSet[V]) SumBy ¶ added in v1.0.228
func (seq SeqSet[V]) SumBy[S constraints.Number](fn func(V) S) S
SumBy maps each element to a numeric value via fn and returns the sum of those values. The fold order is undefined, so fn should be free of order-dependent side effects. An empty sequence yields the zero value of S.
func (SeqSet[V]) Take ¶ added in v1.0.181
Take returns a new iterator with the first n elements. The function creates a new iterator containing the first n elements from the original iterator.
type SeqSlice ¶ added in v1.0.63
SeqSlice is an iterator over sequences of individual values.
func FromChan ¶ added in v1.0.69
FromChan converts a channel into an iterator.
This function takes a channel as input and converts its elements into an iterator, allowing seamless integration of channels into iterator-based processing pipelines. It continuously reads from the channel until it's closed, yielding each element to the provided yield function.
Parameters: - ch (<-chan V): The input channel to convert into an iterator.
Returns: - SeqSlice[V]: An iterator that yields elements from the channel.
Example usage:
ch := make(chan int)
go func() {
defer close(ch)
for i := 1; i <= 5; i++ {
ch <- i
}
}()
// Convert the channel into an iterator and apply filtering and mapping operations.
g.FromChan(ch).
Filter(func(i int) bool { return i%2 == 0 }). // Filter even numbers.
Map(func(i int) int { return i * 2 }). // Double each element.
Collect(). // Collect the results into a slice.
Print() // Print the collected results.
Output: Slice[4, 8]
The resulting iterator will yield elements from the provided channel, filtering out odd numbers, doubling each even number, and finally collecting the results into a slice.
func Range ¶ added in v1.0.156
func Range[T constraints.Integer](start, stop T, step ...T) SeqSlice[T]
Range returns a SeqSlice[T] yielding a sequence of integers of type T, starting at start, incrementing by step, and ending before stop (exclusive).
- If step is omitted, it defaults to 1.
- If step is 0, the sequence is empty.
- If step does not move toward stop (e.g., positive step with start > stop), the sequence is empty.
Examples:
- Range(0, 5) yields [0, 1, 2, 3, 4]
- Range(5, 0, -1) yields [5, 4, 3, 2, 1]
func RangeInclusive ¶ added in v1.0.176
func RangeInclusive[T constraints.Integer](start, stop T, step ...T) SeqSlice[T]
RangeInclusive returns a SeqSlice[T] yielding a sequence of integers of type T, starting at start, incrementing by step, and ending at stop (inclusive).
- If step is omitted, it defaults to 1.
- If step is 0, the sequence is empty.
- If step does not move toward stop (e.g., positive step with start > stop), the sequence is empty.
Examples:
- RangeInclusive(0, 5) yields [0, 1, 2, 3, 4, 5]
- RangeInclusive(5, 0, -1) yields [5, 4, 3, 2, 1, 0]
func (SeqSlice[V]) All ¶ added in v1.0.63
All checks whether all elements in the iterator satisfy the provided condition. This function is useful when you want to determine if all elements in an iterator meet a specific criteria.
Parameters: - fn func(V) bool: A function that returns a boolean indicating whether the element satisfies the condition.
Returns: - bool: True if all elements in the iterator satisfy the condition, false otherwise.
Example usage:
slice := g.SliceOf(1, 2, 3, 4, 5, 6, 7, -1, -2)
isPositive := func(num int) bool { return num > 0 }
allPositive := slice.Iter().All(isPositive)
The resulting allPositive will be true if all elements returned by the iterator are positive.
func (SeqSlice[V]) Any ¶ added in v1.0.63
Any checks whether any element in the iterator satisfies the provided condition. This function is useful when you want to determine if at least one element in an iterator meets a specific criteria.
Parameters: - fn func(V) bool: A function that returns a boolean indicating whether the element satisfies the condition.
Returns: - bool: True if at least one element in the iterator satisfies the condition, false otherwise.
Example usage:
slice := g.Slice[int]{1, 3, 5, 7, 9}
isEven := func(num int) bool { return num%2 == 0 }
anyEven := slice.Iter().Any(isEven)
The resulting anyEven will be true if at least one element returned by the iterator is even.
func (SeqSlice[V]) Chain ¶ added in v1.0.63
Chain concatenates the current iterator with other iterators, returning a new iterator.
The function creates a new iterator that combines the elements of the current iterator with elements from the provided iterators in the order they are given.
Params:
- seqs ([]SeqSlice[V]): Other iterators to be concatenated with the current iterator.
Returns:
- sequence[V]: A new iterator containing elements from the current iterator and the provided iterators.
Example usage:
iter1 := g.Slice[int]{1, 2, 3}.Iter()
iter2 := g.Slice[int]{4, 5, 6}.Iter()
iter1.Chain(iter2).Collect().Print()
Output: [1, 2, 3, 4, 5, 6]
The resulting iterator will contain elements from both iterators in the specified order.
func (SeqSlice[V]) Chan ¶ added in v1.0.205
Chan converts the iterator into a channel, optionally with context(s).
The function converts the elements of the iterator into a channel for streaming purposes. Optionally, it accepts context(s) to handle cancellation or timeout scenarios.
Params:
- ctxs (context.Context): Optional context(s) to control the channel behavior (e.g., cancellation).
Returns:
- chan V: A channel containing the elements from the iterator.
Example usage:
iter := g.Slice[int]{1, 2, 3}.Iter()
ctx, cancel := context.WithCancel(context.Background())
defer cancel() // Ensure cancellation to avoid goroutine leaks.
ch := iter.Chan(ctx)
for val := range ch {
fmt.Println(val)
}
The resulting channel allows streaming elements from the iterator with optional context handling.
func (SeqSlice[V]) ChunkBy ¶ added in v1.0.228
ChunkBy groups CONSECUTIVE elements of the sequence into chunks based on a custom equality function. It is not an SQL-style GroupBy: elements are never reordered or bucketed by key, so equal elements that are not adjacent end up in different chunks.
The provided function `fn` takes two consecutive elements `a` and `b` and returns `true` if they belong to the same chunk, or `false` if a new chunk should start. The function returns a `SeqSlices[V]`, where each `[]V` represents a run of consecutive elements that satisfy the provided equality condition.
Notes:
- Each chunk is returned as a copy of the elements, since `SeqSlice` does not guarantee that elements share the same backing array.
Parameters:
- fn (func(a, b V) bool): Function that determines whether two consecutive elements belong to the same chunk.
Returns:
- SeqSlices[V]: An iterator yielding slices, each containing one chunk.
Example usage:
slice := g.SliceOf(1, 1, 2, 3, 2, 3, 4)
chunks := slice.Iter().ChunkBy(func(a, b int) bool { return a <= b }).Collect()
// Output: [Slice[1, 1, 2, 3] Slice[2, 3, 4]]
The resulting iterator will yield runs of consecutive elements according to the provided function.
func (SeqSlice[V]) Chunks ¶ added in v1.0.63
Chunks returns an iterator that yields chunks of elements of the specified size.
The function creates a new iterator that yields chunks of elements from the original iterator, with each chunk containing elements of the specified size.
Params:
- n (Int): The size of each chunk.
Returns:
- SeqSlices[V]: An iterator yielding chunks of elements of the specified size.
Example usage:
slice := g.Slice[int]{1, 2, 3, 4, 5, 6}
chunks := slice.Iter().Chunks(2).Collect()
Output: [Slice[1, 2] Slice[3, 4] Slice[5, 6]]
The resulting iterator will yield chunks of elements, each containing the specified number of elements.
func (SeqSlice[V]) Collect ¶ added in v1.0.63
Collect gathers all elements from the iterator into a Slice.
func (SeqSlice[V]) Combinations ¶ added in v1.0.63
Combinations generates all combinations of length 'n' from the sequence.
func (SeqSlice[V]) Context ¶ added in v1.0.181
Context allows the iteration to be controlled with a context.Context.
func (SeqSlice[V]) Count ¶ added in v1.0.63
Count consumes the iterator, counting the number of iterations and returning it.
func (SeqSlice[V]) CounterBy ¶ added in v1.0.228
func (seq SeqSlice[V]) CounterBy[K comparable](fn func(V) K) SeqMapOrd[K, Int]
CounterBy consumes the sequence and returns an ordered map from fn(element) to the number of elements that produced that key: fn is applied to every element, and elements whose keys collide are merged into one bucket with their counts summed. Key order is first-seen. The key type must be comparable; for identity counting pass the identity function (func(v V) V { return v }).
Example usage:
words.Iter().CounterBy(func(w String) Int { return w.Len() })
// MapOrd{5:2, 4:1} — counts by word length, in first-seen order
func (SeqSlice[V]) Cycle ¶ added in v1.0.63
Cycle returns an iterator that endlessly repeats the elements of the current sequence.
func (SeqSlice[V]) Dedup ¶ added in v1.0.63
Dedup creates a new iterator that removes consecutive duplicate elements from the original iterator, leaving only one occurrence of each unique element. If the iterator is sorted, all elements will be unique.
Parameters: - None
Returns: - SeqSlice[V]: A new iterator with consecutive duplicates removed.
Example usage:
slice := g.Slice[int]{1, 2, 2, 3, 4, 4, 4, 5}
iter := slice.Iter().Dedup()
result := iter.Collect()
result.Print()
Output: [1 2 3 4 5]
The resulting iterator will contain only unique elements, removing consecutive duplicates.
func (SeqSlice[V]) Enumerate ¶ added in v1.0.63
Enumerate adds an index to each element in the iterator.
Returns:
- SeqMapOrd[Int, V] An iterator with each element of type Pair[Int, V], where the first element of the pair is the index and the second element is the original element from the iterator.
Example usage:
ps := g.SliceOf[g.String]("bbb", "ddd", "xxx", "aaa", "ccc").
Iter().
Enumerate().
Collect()
ps.Print()
Output: MapOrd{0:bbb, 1:ddd, 2:xxx, 3:aaa, 4:ccc}
func (SeqSlice[V]) Exclude ¶ added in v1.0.63
Exclude returns a new iterator excluding elements that satisfy the provided function.
The function applies the provided function to each element of the iterator. If the function returns true for an element, that element is excluded from the resulting iterator.
Parameters:
- fn (func(V) bool): The function to be applied to each element of the iterator to determine if it should be excluded from the result.
Returns:
- SeqSlice[V]: A new iterator containing the elements that do not satisfy the given condition.
Example usage:
slice := g.Slice[int]{1, 2, 3, 4, 5}
notEven := slice.Iter().
Exclude(
func(val int) bool {
return val%2 == 0
}).
Collect()
notEven.Print()
Output: [1, 3, 5]
The resulting iterator will contain only the elements that do not satisfy the provided function.
func (SeqSlice[V]) Filter ¶ added in v1.0.63
Filter returns a new iterator containing only the elements that satisfy the provided function.
The function applies the provided function to each element of the iterator. If the function returns true for an element, that element is included in the resulting iterator.
Parameters:
- fn (func(V) bool): The function to be applied to each element of the iterator to determine if it should be included in the result.
Returns:
- SeqSlice[V]: A new iterator containing the elements that satisfy the given condition.
Example usage:
slice := g.Slice[int]{1, 2, 3, 4, 5}
even := slice.Iter().
Filter(
func(val int) bool {
return val%2 == 0
}).
Collect()
even.Print()
Output: [2 4].
The resulting iterator will contain only the elements that satisfy the provided function.
func (SeqSlice[V]) FilterMap ¶ added in v1.0.184
FilterMap applies a function to each element and filters out None results.
The function transforms and filters in a single pass. Elements where the function returns None are filtered out, and elements where it returns Some are unwrapped and included in the result.
Params:
- fn (func(V) Option[V]): The function that transforms and filters elements. Returns Some(value) to include the transformed value, or None to filter it out.
Returns:
- SeqSlice[V]: A sequence containing only the successfully transformed elements.
Example usage:
strings := g.Slice[string]{"1", "2", "abc", "3", "xyz"}.Iter()
numbers := strings.FilterMap(func(s string) Option[int] {
if n, err := strconv.Atoi(s); err == nil {
return Some(n)
}
return None[int]()
})
// numbers will yield: 1, 2, 3
values := g.Slice[int]{1, -2, 3, -4, 5}.Iter()
positiveDoubled := values.FilterMap(func(n int) Option[int] {
if n > 0 {
return Some(n * 2)
}
return None[int]()
})
// positiveDoubled will yield: 2, 6, 10
func (SeqSlice[V]) Find ¶ added in v1.0.63
Find searches for an element in the iterator that satisfies the provided function.
The function iterates through the elements of the iterator and returns the first element for which the provided function returns true.
Params:
- fn (func(V) bool): The function used to test elements for a condition.
Returns:
- Option[V]: An Option containing the first element that satisfies the condition; None if not found.
Example usage:
iter := g.Slice[int]{1, 2, 3, 4, 5}.Iter()
found := // func(i int) bool {
return i == 2
}.Find()
if found.IsSome() {
fmt.Println("Found:", found.Some())
} else {
fmt.Println("Not found.")
}
The resulting Option may contain the first element that satisfies the condition, or None if not found.
func (SeqSlice[V]) FindMap ¶ added in v1.0.228
FindMap applies fn to each element and returns the first Some result, or None if fn returns None for every element.
func (SeqSlice[V]) FlatMap ¶ added in v1.0.184
FlatMap applies a function to each element that returns an iterator, then flattens the results.
The function transforms each element into a sequence and then concatenates all sequences into a single flat sequence.
Params:
- fn (func(V) SeqSlice[V]): The function that transforms each element into a sequence.
Returns:
- SeqSlice[V]: A flattened sequence containing all elements from the transformed sequences.
Example usage:
words := g.Slice[string]{"hello world", "foo bar"}.Iter()
chars := words.FlatMap(func(s string) SeqSlice[string] {
return g.String(s).Split("")
})
// chars will yield: "h", "e", "l", "l", "o", " ", "w", "o", "r", "l", "d", "f", "o", "o", " ", "b", "a", "r"
numbers := g.Slice[int]{1, 2, 3}.Iter()
expanded := numbers.FlatMap(func(n int) SeqSlice[int] {
return g.Slice[int]{n, n*10, n*100}.Iter()
})
// expanded will yield: 1, 10, 100, 2, 20, 200, 3, 30, 300
func (SeqSlice[V]) Flatten ¶ added in v1.0.63
Flatten flattens an iterator of iterators into a single iterator.
The function creates a new iterator that flattens a sequence of iterators, returning a single iterator containing elements from each iterator in sequence.
Returns:
- SeqSlice[V]: A single iterator containing elements from the sequence of iterators.
Example usage:
nestedSlice := g.Slice[any]{
1,
g.SliceOf(2, 3),
"abc",
g.SliceOf("def", "ghi"),
g.SliceOf(4.5, 6.7),
}
nestedSlice.Iter().Flatten().Collect().Print()
Output: Slice[1, 2, 3, abc, def, ghi, 4.5, 6.7]
The resulting iterator will contain elements from each iterator in sequence.
func (SeqSlice[V]) Fold ¶ added in v1.0.63
Fold accumulates values in the iterator using a function.
The function iterates through the elements of the iterator, accumulating values using the provided function and an initial value.
Params:
- init (A): The initial value for accumulation. The accumulator type may differ from the element type.
- fn (func(A, V) A): The function that accumulates values; it takes the accumulator and an element and returns the new accumulator.
Returns:
- T: The accumulated value after applying the function to all elements.
Example usage:
slice := g.Slice[int]{1, 2, 3, 4, 5}
sum := slice.Iter().
Fold(0,
func(acc, val int) int {
return acc + val
})
fmt.Println(sum)
Output: 15.
The resulting value will be the accumulation of elements based on the provided function.
func (SeqSlice[V]) ForEach ¶ added in v1.0.63
func (seq SeqSlice[V]) ForEach(fn func(v V))
ForEach iterates through all elements and applies the given function to each.
The function applies the provided function to each element of the iterator.
Params:
- fn (func(V)): The function to apply to each element.
Example usage:
iter := g.Slice[int]{1, 2, 3, 4, 5}.Iter()
func(val V) {
fmt.Println(val) // Replace this with the function logic you need.
}.ForEach()
The provided function will be applied to each element in the iterator.
func (SeqSlice[V]) Inspect ¶ added in v1.0.63
Inspect creates a new iterator that wraps around the current iterator and allows inspecting each element as it passes through.
func (SeqSlice[V]) Intersperse ¶ added in v1.0.80
Intersperse inserts the provided separator between elements of the iterator.
The function creates a new iterator that inserts the given separator between each consecutive pair of elements in the original iterator.
Params:
- sep (V): The separator to intersperse between elements.
Returns:
- SeqSlice[V]: An iterator containing elements with the separator interspersed.
Example usage:
g.Slice[string]{"Hello", "World", "!"}.
Iter().
Intersperse(" ").
Collect().
Join().
Print()
Output: "Hello World !".
The resulting iterator will contain elements with the separator interspersed.
func (SeqSlice[V]) Map ¶ added in v1.0.63
Map transforms each element in the iterator using the given function.
The function creates a new iterator by applying the provided function to each element of the original iterator.
Params:
- fn (func(V) U): The function used to transform elements. The result type may differ from the element type.
Returns:
- SeqSlice[U]: A iterator containing elements transformed by the provided function.
Example usage:
slice := g.Slice[int]{1, 2, 3}
strs := slice.
Iter().
Map(
func(val int) g.String {
return g.Int(val * 2).String()
}).
Collect()
strs.Print()
Output: Slice[2, 4, 6].
The resulting iterator will contain elements transformed by the provided function.
func (SeqSlice[V]) MaxBy ¶ added in v1.0.181
MaxBy returns the maximum element in the sequence using the provided comparison function.
func (SeqSlice[V]) MinBy ¶ added in v1.0.181
Min returns the minimum element in the sequence using the provided comparison function.
func (*SeqSlice[V]) Next ¶ added in v1.0.189
Next extracts the next element from the iterator and advances it.
This method consumes the next element from the iterator and returns it wrapped in an Option. The iterator itself is modified to point to the remaining elements. This is similar to calling Pull() but more convenient for single-element extraction.
Returns: - Option[V]: Some(value) if an element exists, None if the iterator is exhausted.
func (SeqSlice[V]) Partition ¶ added in v1.0.63
Partition divides the elements of the iterator into two separate slices based on a given predicate function.
The function takes a predicate function 'fn', which should return true or false for each element in the iterator. Elements for which 'fn' returns true are collected into the left slice, while those for which 'fn' returns false are collected into the right slice.
Params:
- fn (func(V) bool): The predicate function used to determine the placement of elements.
Returns:
- (Slice[V], Slice[V]): Two slices representing elements that satisfy and don't satisfy the predicate, respectively.
Example usage:
evens, odds := g.Slice[int]{1, 2, 3, 4, 5}.
Iter().
Partition(
func(v int) bool {
return v%2 == 0
})
fmt.Println("Even numbers:", evens) // Output: Even numbers: Slice[2, 4]
fmt.Println("Odd numbers:", odds) // Output: Odd numbers: Slice[1, 3, 5]
The resulting two slices will contain elements separated based on whether they satisfy the predicate or not.
func (SeqSlice[V]) Permutations ¶ added in v1.0.63
Slice[1, 2, 3] Slice[2, 1, 3] Slice[3, 1, 2] Slice[1, 3, 2] Slice[2, 3, 1] Slice[3, 2, 1]
The resulting iterator will contain iterators representing all possible permutations of the elements in the original iterator.
func (SeqSlice[V]) ProductBy ¶ added in v1.0.228
func (seq SeqSlice[V]) ProductBy[S constraints.Number](fn func(V) S) S
ProductBy maps each element to a numeric value via fn and returns their product. An empty sequence yields the multiplicative identity, one.
func (SeqSlice[V]) Pull ¶ added in v1.0.63
Pull converts the "push-style" iterator sequence seq into a "pull-style" iterator accessed by the two functions next and stop.
Next returns the next value in the sequence and a boolean indicating whether the value is valid. When the sequence is over, next returns the zero V and false. It is valid to call next after reaching the end of the sequence or after calling stop. These calls will continue to return the zero V and false.
Stop ends the iteration. It must be called when the caller is no longer interested in next values and next has not yet signaled that the sequence is over (with a false boolean return). It is valid to call stop multiple times and when next has already returned false.
It is an error to call next or stop from multiple goroutines simultaneously.
func (SeqSlice[V]) Range ¶ added in v1.0.63
Range iterates through elements until the given function returns false.
The function iterates through the elements of the iterator and applies the provided function to each element. It stops iteration when the function returns false for an element.
Params:
- fn (func(V) bool): The function that evaluates elements for continuation of iteration.
Example usage:
iter := g.Slice[int]{1, 2, 3, 4, 5}.Iter()
func(val int) bool {
fmt.Println(val) // Replace this with the function logic you need.
return val < 5 // Replace this with the condition for continuing iteration.
}.Range()
The iteration will stop when the provided function returns false for an element.
func (SeqSlice[V]) Reduce ¶ added in v1.0.178
Reduce aggregates elements of the sequence using the provided function. The first element of the sequence is used as the initial accumulator value. If the sequence is empty, it returns None[V].
Params:
- fn (func(V, V) V): Function that combines two values into one.
Returns:
- Option[V]: The accumulated value wrapped in Some, or None if the sequence is empty.
Example:
slice := g.Slice[int]{1, 2, 3, 4, 5}
product := slice.Iter().Reduce(func(a, b int) int { return a * b })
if product.IsSome() {
fmt.Println(product.Some()) // 120
} else {
fmt.Println("empty")
}
func (SeqSlice[V]) Scan ¶ added in v1.0.184
Scan accumulates values of the iterator using a function, yielding all intermediate states.
The function takes an initial accumulator value and a function that combines the accumulator with each element. It yields the initial value followed by each accumulated state.
Params:
- init (A): The initial accumulator value. The accumulator type may differ from the element type. - fn (func(acc A, val V) A): The function that combines the accumulator with each element.
Returns:
- SeqSlice[A]: A sequence of all intermediate accumulator states.
Example usage:
numbers := g.Slice[int]{1, 2, 3, 4}.Iter()
sums := numbers.Scan(0, func(acc, val int) int {
return acc + val
})
// sums will yield: 0, 1, 3, 6, 10
words := g.Slice[string]{"a", "b", "c"}.Iter()
concatenated := words.Scan("", func(acc, val string) string {
return acc + val
})
// concatenated will yield: "", "a", "ab", "abc"
func (SeqSlice[V]) Skip ¶ added in v1.0.63
Skip returns a new iterator skipping the first n elements.
The function creates a new iterator that skips the first n elements of the current iterator and returns an iterator starting from the (n+1)th element.
Params:
- n (uint): The number of elements to skip from the beginning of the iterator.
Returns:
- SeqSlice[V]: An iterator that starts after skipping the first n elements.
Example usage:
iter := g.Slice[int]{1, 2, 3, 4, 5, 6}.Iter()
3.Skip().Collect().Print()
Output: [4, 5, 6]
The resulting iterator will start after skipping the specified number of elements.
func (SeqSlice[V]) SkipWhile ¶ added in v1.0.228
SkipWhile skips elements while the predicate returns true, then yields the rest.
func (SeqSlice[V]) SortBy ¶ added in v1.0.63
SortBy applies a custom sorting function to the elements in the iterator and returns a new iterator containing the sorted elements.
The sorting function 'fn' should take two arguments, 'a' and 'b' of type V, and return true if 'a' should be ordered before 'b', and false otherwise.
Example:
g.SliceOf("a", "c", "b").
Iter().
SortBy(func(a, b string) cmp.Ordering { return b.Cmp(a) }).
Collect().
Print()
Output: Slice[c, b, a]
The returned iterator is of type SeqSlice[V], which implements the iterator interface for further iteration over the sorted elements.
func (SeqSlice[V]) StepBy ¶ added in v1.0.63
StepBy creates a new iterator that iterates over every N-th element of the original iterator. This function is useful when you want to skip a specific number of elements between each iteration.
Parameters: - n uint: The step size, indicating how many elements to skip between each iteration.
Returns: - SeqSlice[V]: A new iterator that produces elements from the original iterator with a step size of N.
Example usage:
slice := g.Slice[int]{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
iter := slice.Iter().StepBy(3)
result := iter.Collect()
result.Print()
Output: [1 4 7 10]
The resulting iterator will produce elements from the original iterator with a step size of N.
func (SeqSlice[V]) SumBy ¶ added in v1.0.228
func (seq SeqSlice[V]) SumBy[S constraints.Number](fn func(V) S) S
SumBy maps each element to a numeric value via fn and returns the sum of those values. An empty sequence yields the zero value of S. The result type S is chosen by fn, independent of the element type V.
Params:
- fn (func(V) S): Projects an element to the numeric value to be summed.
Returns:
- S: The sum of the projected values.
Example usage:
words := g.SliceOf[g.String]("a", "bb", "ccc")
total := words.Iter().SumBy(func(s g.String) g.Int { return s.Len() })
fmt.Println(total) // 6
func (SeqSlice[V]) Take ¶ added in v1.0.63
Take returns a new iterator with the first n elements. The function creates a new iterator containing the first n elements from the original iterator.
func (SeqSlice[V]) TakeWhile ¶ added in v1.0.228
TakeWhile yields elements while the predicate returns true, stopping at the first false.
func (SeqSlice[V]) TryMap ¶ added in v1.0.228
TryMap applies a fallible transform to each element and enters the Result pipeline, producing a SeqResult[U]. It is the bridge from a plain sequence into SeqResult: map each element to a Result[U] and continue with the SeqResult terminals (TryCollect, SumBy, ...), which choose the Err policy.
TryMap itself is lazy and consumer-driven: it yields fn(v) for each element and leaves the Err policy to the terminal — TryCollect / Fold / Reduce / SumBy / All / Any / First short-circuit on the first Err, while Collect and Count traverse every element.
Example usage:
// "abc" fails to parse -> the whole batch short-circuits
res := g.SliceOf[g.String]("1", "2", "3").
Iter().
TryMap(g.String.TryInt).
TryCollect() // Ok(Slice[1, 2, 3])
sum := g.SliceOf[g.String]("1", "2", "3").
Iter().
TryMap(g.String.TryInt).
SumBy(f.Id) // Ok(6)
func (SeqSlice[V]) Unique ¶ added in v1.0.63
Unique returns an iterator with only unique elements.
The function returns an iterator containing only the unique elements from the original iterator.
Returns:
- SeqSlice[V]: An iterator containing unique elements from the original iterator.
Example usage:
slice := g.Slice[int]{1, 2, 3, 2, 4, 5, 3}
unique := slice.Iter().Unique().Collect()
unique.Print()
Output: [1, 2, 3, 4, 5].
The resulting iterator will contain only unique elements from the original iterator.
func (SeqSlice[V]) Windows ¶ added in v1.0.63
Windows returns an iterator that yields sliding windows of elements of the specified size.
The function creates a new iterator that yields windows of elements from the original iterator, where each window is a slice containing elements of the specified size and moves one element at a time.
Params:
- n (int): The size of each window.
Returns:
- SeqSlices[V]: An iterator yielding sliding windows of elements of the specified size.
Example usage:
slice := g.Slice[int]{1, 2, 3, 4, 5, 6}
windows := slice.Iter().Windows(3).Collect()
Output: [Slice[1, 2, 3] Slice[2, 3, 4] Slice[3, 4, 5] Slice[4, 5, 6]]
The resulting iterator will yield sliding windows of elements, each containing the specified number of elements.
type SeqSlices ¶ added in v1.0.63
SeqSlices is an iterator over slices of sequences of individual values.
func (SeqSlices[V]) Collect ¶ added in v1.0.63
Collect gathers all elements from the iterator into a []Slice.
func (SeqSlices[V]) Filter ¶ added in v1.0.225
Filter returns a new iterator containing only the groups (sub-slices) that satisfy the provided function.
The function applies the provided function to each group produced by the original iterator. If the function returns true for a group, that group is included in the resulting iterator.
Params:
- fn (func(Slice[V]) bool): The predicate applied to each group.
Returns:
- SeqSlices[V]: An iterator yielding the groups that satisfy the given condition.
Example usage:
slice := g.Slice[int]{1, 2, 3, 4, 5, 6}
pairs := slice.Iter().
Chunks(2).
Filter(func(chunk g.Slice[int]) bool { return chunk.Len() == 2 }).
Collect()
func (SeqSlices[V]) Flatten ¶ added in v1.0.225
Flatten flattens the iterator of groups (sub-slices) into a single SeqSlice[V], yielding the elements of each group in order.
Returns:
- SeqSlice[V]: A single iterator containing the elements from each group in sequence.
Example usage:
slice := g.Slice[int]{1, 2, 3, 4, 5, 6}
flat := slice.Iter().Chunks(2).Flatten().Collect()
// Output: Slice[1, 2, 3, 4, 5, 6]
func (SeqSlices[V]) ForEach ¶ added in v1.0.225
ForEach iterates through all groups (sub-slices) and applies the given function to each.
Params:
- fn (func(Slice[V])): The function to apply to each group.
Example usage:
slice := g.Slice[int]{1, 2, 3, 4}
slice.Iter().Chunks(2).ForEach(func(chunk g.Slice[int]) {
fmt.Println(chunk)
})
func (SeqSlices[V]) Map ¶ added in v1.0.225
Map transforms each group (sub-slice) in the iterator using the given function.
The function creates a new lazy iterator by applying the provided function to each group produced by the original iterator, preserving the streaming pipeline.
Params:
- fn (func(Slice[V]) Slice[V]): The function used to transform each group.
Returns:
- SeqSlices[V]: An iterator yielding the transformed groups.
Example usage:
slice := g.Slice[int]{1, 2, 3, 4}
doubled := slice.Iter().
Chunks(2).
Map(func(chunk g.Slice[int]) g.Slice[int] {
return chunk.Iter().Map(func(v int) int { return v * 2 }).Collect()
}).
Collect()
// Output: [Slice[2, 4] Slice[6, 8]]
type Set ¶
type Set[T comparable] map[T]Unit
Set is a generic alias for a set implemented using a map.
func NewSet ¶
func NewSet[T comparable](size ...Int) Set[T]
NewSet creates a new Set of the specified size or an empty Set if no size is provided.
func SetFromSlice ¶ added in v1.0.228
func SetFromSlice[T comparable](s Slice[T]) Set[T]
SetFromSlice builds a Set from a slice. Unlike the variadic SetOf, it takes the slice directly, so it can be passed as a first-class function — e.g. as the collect step after a chain: res.TryCollect().Map(SetFromSlice).
func SetOf ¶
func SetOf[T comparable](values ...T) Set[T]
SetOf creates a new generic set containing the provided elements.
func (Set[T]) ContainsAll ¶
ContainsAll checks if the Set contains all elements from another Set.
func (Set[T]) ContainsAny ¶
ContainsAny checks if the Set contains any element from another Set.
func (Set[T]) Difference ¶
Difference returns the difference between the current set and another set, i.e., elements present in the current set but not in the other set.
Parameters:
- other Set[T]: The other set to calculate the difference with.
Returns:
- Set[T]: A new Set containing the difference between the two sets.
Example usage:
s1 := g.SetOf(1, 2, 3, 4, 5) s2 := g.SetOf(4, 5, 6, 7, 8) diff := s1.Difference(s2)
The resulting diff will be: [1, 2, 3].
func (Set[T]) Disjoint ¶ added in v1.0.228
Disjoint reports whether the set has no elements in common with other. It is the complement of ContainsAny.
func (Set[T]) Insert ¶ added in v1.0.140
func (s Set[T]) Insert(values ...T)
Insert adds the provided elements to the set.
func (Set[T]) Intersection ¶
Intersection returns the intersection of the current set and another set, i.e., elements present in both sets.
Parameters:
- other Set[T]: The other set to calculate the intersection with.
Returns:
- Set[T]: A new Set containing the intersection of the two sets.
Example usage:
s1 := g.SetOf(1, 2, 3, 4, 5) s2 := g.SetOf(4, 5, 6, 7, 8) intersection := s1.Intersection(s2)
The resulting intersection will be: [4, 5].
func (Set[T]) Iter ¶
Iter returns an iterator (SeqSet[T]) for the Set, allowing for sequential iteration over its elements. It is commonly used in combination with higher-order functions, such as 'ForEach' or 'SetMap', to perform operations on each element of the Set.
Returns:
A SeqSet[T], which can be used for sequential iteration over the elements of the Set.
Example usage:
iter := g.SetOf(1, 2, 3).Iter()
func(val T) {
fmt.Println(val) // Replace this with the function logic you need.
}.ForEach()
The 'Iter' method provides a convenient way to traverse the elements of a Set in a functional style, enabling operations like mapping or filtering.
func (Set[T]) Print ¶
Print writes the elements of the Set to the standard output (console) and returns the Set unchanged.
func (Set[T]) Println ¶ added in v1.0.122
Println writes the elements of the Set to the standard output (console) with a newline and returns the Set unchanged.
func (Set[T]) Remove ¶
Remove removes the specified value from the Set and returns true if it was present.
func (Set[T]) Slice ¶ added in v1.0.205
Slice returns a new Slice with the same elements as the Set[T].
func (Set[T]) Subset ¶
Subset checks if the current set 's' is a subset of the provided 'other' set. A set 's' is a subset of 'other' if all elements of 's' are also elements of 'other'.
Parameters:
- other Set[T]: The other set to compare with.
Returns:
- bool: true if 's' is a subset of 'other', false otherwise.
Example usage:
s1 := g.SetOf(1, 2, 3) s2 := g.SetOf(1, 2, 3, 4, 5) isSubset := s1.Subset(s2) // Returns true
func (Set[T]) Superset ¶
Superset checks if the current set 's' is a superset of the provided 'other' set. A set 's' is a superset of 'other' if all elements of 'other' are also elements of 's'.
Parameters:
- other Set[T]: The other set to compare with.
Returns:
- bool: true if 's' is a superset of 'other', false otherwise.
Example usage:
s1 := g.SetOf(1, 2, 3, 4, 5) s2 := g.SetOf(1, 2, 3) isSuperset := s1.Superset(s2) // Returns true
func (Set[T]) SymmetricDifference ¶
SymmetricDifference returns the symmetric difference between the current set and another set, i.e., elements present in either the current set or the other set but not in both.
Parameters:
- other Set[T]: The other set to calculate the symmetric difference with.
Returns:
- Set[T]: A new Set containing the symmetric difference between the two sets.
Example usage:
s1 := g.SetOf(1, 2, 3, 4, 5) s2 := g.SetOf(4, 5, 6, 7, 8) symDiff := s1.SymmetricDifference(s2)
The resulting symDiff will be: [1, 2, 3, 6, 7, 8].
func (Set[T]) Transform ¶ added in v1.0.89
Transform applies a transformation function to the Set and returns the result.
func (Set[T]) Union ¶
Union returns a new set containing the unique elements of the current set and the provided other set.
Parameters:
- other Set[T]: The other set to create the union with.
Returns:
- Set[T]: A new Set containing the unique elements of the current set and the provided other set.
Example usage:
s1 := g.SetOf(1, 2, 3) s2 := g.SetOf(3, 4, 5) union := s1.Union(s2)
The resulting union set will be: [1, 2, 3, 4, 5].
type Slice ¶
type Slice[T any] []T
Slice is a generic alias for a slice.
func NewSlice ¶
NewSlice creates a new Slice of the given generic type T with the specified length and capacity. The size variadic parameter can have zero, one, or two integer values. If no values are provided, an empty Slice with a length and capacity of 0 is returned. If one value is provided, it sets both the length and capacity of the Slice. If two values are provided, the first value sets the length and the second value sets the capacity.
Parameters:
- size ...Int: A variadic parameter specifying the length and/or capacity of the Slice
Returns:
- Slice[T]: A new Slice of the specified generic type T with the given length and capacity
Example usage:
s1 := g.NewSlice[int]() // Creates an empty Slice of type int s2 := g.NewSlice[int](5) // Creates an Slice with length and capacity of 5 s3 := g.NewSlice[int](3, 10) // Creates an Slice with length of 3 and capacity of 10
func (Slice[T]) Append ¶
Append appends the provided elements to the slice and returns the modified slice.
func (Slice[T]) AppendUnique ¶ added in v1.0.143
AppendUnique appends unique elements from the provided arguments to the current slice.
The function iterates over the provided elements and checks if they are already present in the slice. If an element is not already present, it is appended to the slice. The resulting slice is returned, containing the unique elements from both the original slice and the provided elements.
Parameters:
- elems (...T): A variadic list of elements to be appended to the slice.
Returns:
- Slice[T]: A new slice containing the unique elements from both the original slice and the provided elements.
Example usage:
slice := g.Slice[int]{1, 2, 3, 4, 5}
slice = slice.AppendUnique(3, 4, 5, 6, 7)
fmt.Println(slice)
Output: [1 2 3 4 5 6 7].
func (Slice[T]) BinarySearch ¶ added in v1.0.228
BinarySearch searches a sorted slice for value using the comparator fn and returns Some(index) if an equal element is found, or None otherwise. The slice must be sorted in ascending order according to fn (see IsSortedBy).
func (Slice[T]) ContainsAll ¶
ContainsAll checks if the Slice contains all elements from another Slice.
func (Slice[T]) ContainsAny ¶
ContainsAny checks if the Slice contains any element from another Slice.
func (Slice[T]) ContainsBy ¶ added in v1.0.65
ContainsBy returns true if the slice contains an element that satisfies the provided function fn, false otherwise.
func (*Slice[T]) DedupBy ¶ added in v1.0.228
DedupBy removes consecutive elements considered equal by eq, keeping the first of each run, in place. It is the eager, in-place counterpart of the lazy SeqSlice.Dedup. Only adjacent duplicates are removed, so sort first for a global dedup.
func (Slice[T]) EqBy ¶ added in v1.0.65
EqBy reports whether two slices are equal using an equality function on each pair of elements. If the lengths are different, EqBy returns false. Otherwise, the elements are compared in increasing index order, and the comparison stops at the first index for which eq returns false.
func (Slice[T]) Fill ¶
func (sl Slice[T]) Fill(val T)
Fill fills the slice with the specified value. This function is useful when you want to create an Slice with all elements having the same value. This method modifies the original slice in place.
Parameters:
- val T: The value to fill the Slice with.
Returns:
- Slice[T]: A reference to the original Slice filled with the specified value.
Example usage:
slice := g.Slice[int]{0, 0, 0}
slice.Fill(5)
The modified slice will now contain: 5, 5, 5.
func (Slice[T]) Get ¶
Get returns the element at the given index, handling negative indices as counting from the end of the slice.
func (Slice[T]) Grow ¶
Grow increases the slice's capacity, if necessary, to guarantee space for another n elements. After Grow(n), at least n elements can be appended to the slice without another allocation. If n is negative or too large to allocate the memory, Grow panics.
func (Slice[T]) Heap ¶ added in v1.0.205
Heap converts the slice to a min/max heap with the specified comparison function.
The comparison function should return:
- cmp.Less if a < b (for min heap)
- cmp.Greater if a > b (for max heap)
- cmp.Equal if a == b
Example usage:
slice := g.SliceOf(5, 2, 8, 1, 9)
minHeap := slice.Heap(cmp.Cmp[int]) // Min heap: Pop() returns smallest
maxHeap := slice.Heap(func(a, b int) cmp.Ordering {
return cmp.Cmp(b, a)
}) // Max heap: Pop() returns largest
Time complexity: O(n) Space complexity: O(n) - creates a copy of the slice
Heap panics if compareFn is nil, mirroring NewHeap, since a nil comparison function would otherwise nil-deref on the first Push.
func (Slice[T]) Index ¶
Index returns the index of the first occurrence of the specified value in the slice, or -1 if not found.
func (Slice[T]) IndexBy ¶ added in v1.0.65
IndexBy returns the index of the first element in the slice satisfying the custom comparison function provided by the user. It iterates through the slice and applies the comparison function to each element and the target value. If the comparison function returns true for any pair of elements, it returns the index of that element. If no such element is found, it returns -1.
func (*Slice[T]) Insert ¶
Insert inserts values at the specified index in the slice and modifies the original slice.
Panics if the index is out of range. A negative index counts from the end of the slice; i == Len() appends at the end.
Parameters:
- i Int: The index at which to insert the new values.
- values ...T: A variadic list of values to insert at the specified index.
Example usage:
slice := g.Slice[string]{"a", "b", "c", "d"}
slice.Insert(2, "e", "f")
The resulting slice will be: ["a", "b", "e", "f", "c", "d"].
func (Slice[T]) IsSortedBy ¶ added in v1.0.193
IsSortedBy checks if the slice is sorted according to the provided comparison function.
The function takes a custom comparison function as an argument and checks if the elements are sorted according to the provided logic.
Parameters:
- fn func(a, b T) cmp.Ordering: A comparison function that defines the sort order.
Returns:
- bool: true if the slice is sorted according to the comparison function, false otherwise.
Example usage:
sl := g.SliceOf(1, 2, 3, 4, 5)
sorted := sl.IsSortedBy(func(a, b int) cmp.Ordering { return cmp.Cmp(a, b) }) // returns true
func (Slice[T]) Iter ¶
Iter returns an iterator (SeqSlice[T]) for the Slice, allowing for sequential iteration over its elements. It is commonly used in combination with higher-order functions, such as 'ForEach', to perform operations on each element of the Slice.
Returns:
A SeqSlice[T], which can be used for sequential iteration over the elements of the Slice.
Example usage:
slice := g.Slice[int]{1, 2, 3, 4, 5}
iterator := slice.Iter()
iterator.ForEach(func(element int) {
// Perform some operation on each element
fmt.Println(element)
})
The 'Iter' method provides a convenient way to traverse the elements of a Slice in a functional style, enabling operations like mapping or filtering.
func (Slice[T]) IterReverse ¶ added in v1.0.96
IterReverse returns an iterator (SeqSlice[T]) for the Slice that allows for sequential iteration over its elements in reverse order. This method is useful when you need to traverse the elements from the end to the beginning.
Returns:
A SeqSlice[T], which can be used for sequential iteration over the elements of the Slice in reverse order.
Example usage:
slice := g.Slice[int]{1, 2, 3, 4, 5}
iterator := slice.IterReverse()
iterator.ForEach(func(element int) {
// Perform some operation on each element in reverse order
fmt.Println(element)
})
The 'IterReverse' method enhances the functionality of the Slice by providing an alternative way to iterate through its elements, enhancing flexibility in how data within a Slice is accessed and manipulated.
func (Slice[T]) Join ¶
Join joins the elements in the slice into a single String, separated by the provided separator (if any).
func (Slice[T]) NeBy ¶ added in v1.0.68
NeBy reports whether two slices are not equal using an inequality function on each pair of elements. If the lengths are different, NeBy returns true. Otherwise, the elements are compared in increasing index order, and the comparison stops at the first index for which fn returns true.
func (Slice[T]) PartitionPoint ¶ added in v1.0.228
PartitionPoint returns the index of the first element for which pred returns false, assuming the slice is partitioned so that all elements satisfying pred come first. If pred is true for every element, it returns the slice length. Runs in O(log n).
func (*Slice[T]) Pop ¶
Pop removes and returns the last element of the slice. It mutates the original slice by removing the last element. It returns None if the slice is empty.
func (Slice[T]) Print ¶
Print writes the elements of the Slice to the standard output (console) and returns the Slice unchanged.
func (Slice[T]) Println ¶ added in v1.0.122
Println writes the elements of the Slice to the standard output (console) with a newline and returns the Slice unchanged.
func (*Slice[T]) Push ¶ added in v1.0.140
func (sl *Slice[T]) Push(elems ...T)
Push appends the provided elements to the slice and modifies the original slice.
func (*Slice[T]) PushUnique ¶ added in v1.0.143
func (sl *Slice[T]) PushUnique(elems ...T)
PushUnique appends unique elements from the provided arguments to the current slice.
The function iterates over the provided elements and checks if they are already present in the slice. If an element is not already present, it is appended to the slice.
Parameters:
- elems (...T): A variadic list of elements to be appended to the slice.
Example usage:
slice := g.Slice[int]{1, 2, 3, 4, 5}
slice.PushUnique(3, 4, 5, 6, 7)
fmt.Println(slice)
Output: [1 2 3 4 5 6 7].
func (Slice[T]) Random ¶
func (sl Slice[T]) Random() T
Random returns a random element from the slice. If the slice is empty, the zero value of type T is returned.
Returns:
- T: A random element from the slice.
Example usage:
slice := g.Slice[int]{1, 2, 3, 4, 5}
randomElement := slice.Random()
fmt.Println(randomElement)
Output: <any random element from the slice>.
func (Slice[T]) RandomRange ¶
RandomRange returns a new slice containing a random sample of elements from a subrange of the original slice. The sampling is done without replacement, meaning that each element can only appear once in the result.
func (Slice[T]) RandomSample ¶
RandomSample returns a new slice containing a random sample of elements from the original slice. The sampling is done without replacement, meaning that each element can only appear once in the result.
Parameters:
- sequence int: The number of unique elements to include in the random sample.
Returns:
- Slice[T]: A new Slice containing the random sample of unique elements.
Example usage:
slice := g.Slice[int]{1, 2, 3, 4, 5, 6, 7, 8, 9}
sample := slice.RandomSample(3)
The resulting sample will contain 3 unique elements randomly selected from the original slice.
func (*Slice[T]) Remove ¶ added in v1.0.202
Remove removes an element or a range of elements from the Slice in-place. It modifies the original Slice by creating two slices: one from the beginning of the Slice up to the specified `start` index (exclusive), and another from the `end` index (inclusive) to the end of the Slice. These two slices are then concatenated to form the modified Slice.
Parameters:
- start (Int): The starting index of the element or range to be removed.
- end (Int, optional): The end index of the range to be removed. If omitted, only the element at the `start` index is removed.
Remove removes and returns the element at the specified index. Returns None if index is out of bounds. Negative indices are supported: -1 refers to the last element, etc.
func (*Slice[T]) Replace ¶
Replace replaces the elements of sl[i:j] with the given values, and modifies the original slice in place. Replace panics if sl[i:j] is not a valid slice of sl.
Parameters:
- i int: The starting index of the slice to be replaced.
- j int: The ending index of the slice to be replaced.
- values ...T: A variadic list of values to replace the existing slice.
Example usage:
slice := g.Slice[string]{"a", "b", "c", "d"}
slice.Replace(1, 3, "e", "f")
After the Replace operation, the resulting slice will be: ["a", "e", "f", "d"].
func (*Slice[T]) Retain ¶ added in v1.0.228
Retain keeps only the elements for which fn returns true, removing the rest in place while preserving order. It is the in-place counterpart of Deque.Retain.
func (Slice[T]) Reverse ¶
func (sl Slice[T]) Reverse()
Reverse reverses the order of the elements in the slice. This method modifies the original slice in place.
Returns:
- Slice[T]: The modified slice with the elements reversed.
Example usage:
slice := g.Slice[int]{1, 2, 3, 4, 5} slice.Reverse() fmt.Println(slice)
Output: [5 4 3 2 1].
func (Slice[T]) Set ¶
Set sets the value at the specified index in the slice and returns the previous value wrapped in Some. If the index is out of bounds, the slice is left unchanged and None is returned, mirroring Deque.Set. This method modifies the original slice in place. Negative indices count from the end.
Parameters:
- index (Int): The index at which to set the new value. - val (T): The new value to be set at the specified index.
Returns:
- Option[T]: The previous value at the index, or None if the index is out of bounds.
Example usage:
slice := g.Slice[int]{1, 2, 3, 4, 5} old := slice.Set(2, 99) // Some(3) fmt.Println(slice)
Output: [1 2 99 4 5].
func (Slice[T]) Shuffle ¶
func (sl Slice[T]) Shuffle()
Shuffle shuffles the elements in the slice randomly. This method modifies the original slice in place.
Example usage:
slice := g.Slice[int]{1, 2, 3, 4, 5} slice.Shuffle() fmt.Println(slice)
Output: A randomly shuffled version of the original slice, e.g., [4 1 5 2 3].
func (Slice[T]) SortBy ¶
SortBy sorts the elements in the slice using the provided comparison function. It modifies the original slice in place.
The comparison function should return:
- cmp.Less if a should come before b
- cmp.Greater if a should come after b
- cmp.Equal if a and b are considered equal
The sort is not guaranteed to be stable: the relative order of elements that compare equal may change.
Parameters:
- fn func(a, b T) cmp.Ordering: A comparison function reporting the ordering of a relative to b.
Example usage:
sl := NewSlice[int](1, 5, 3, 2, 4) sl.SortBy(func(a, b int) cmp.Ordering { return cmp.Cmp(a, b) }) // sorts in ascending order.
func (Slice[T]) Std ¶
func (sl Slice[T]) Std() []T
Std returns a new slice with the same elements as the Slice[T].
func (Slice[T]) SubSlice ¶
SubSlice returns a new slice containing elements from the current slice between the specified start and end indices, with an optional step parameter to define the increment between elements. Negative start or end indices count from the end of the slice.
Panics if start or end is out of range after negative-index resolution.
Parameters:
- start (Int): The start index of the range.
- end (Int): The end index of the range.
- step (Int, optional): The increment between elements. Defaults to 1 if not provided. If negative, the slice is traversed in reverse order.
Returns:
- Slice[T]: A new slice containing elements from the current slice between the start and end indices, with the specified step.
Example usage:
slice := g.Slice[int]{1, 2, 3, 4, 5, 6, 7, 8, 9}
subSlice := slice.SubSlice(1, 7, 2) // Extracts elements 2, 4, 6
fmt.Println(subSlice)
Output: [2 4 6].
func (Slice[T]) Swap ¶
Swap swaps the elements at the specified indices in the slice. This method modifies the original slice in place.
Panics if either index is out of range. A negative index counts from the end of the slice.
Parameters:
- i (Int): The index of the first element to be swapped.
- j (Int): The index of the second element to be swapped.
Returns:
- Slice[T]: The modified slice with the elements at the specified indices swapped.
Example usage:
slice := g.Slice[int]{1, 2, 3, 4, 5} slice.Swap(1, 3) fmt.Println(slice)
Output: [1 4 3 2 5].
func (Slice[T]) Transform ¶ added in v1.0.89
Transform applies a transformation function to the Slice and returns the result.
func (Slice[T]) Unpack ¶
func (sl Slice[T]) Unpack(vars ...*T)
Unpack assigns values of the slice's elements to the variables passed as pointers. If the number of variables passed is greater than the length of the slice, the function ignores the extra variables.
Parameters:
- vars (...*T): Pointers to variables where the values of the slice's elements will be stored.
Example:
slice := g.Slice[int]{1, 2, 3, 4, 5}
var a, b, c int
slice.Unpack(&a, &b, &c)
fmt.Println(a, b, c) // Output: 1 2 3
type String ¶
type String string
String is an alias for the string type.
func Format ¶
Format processes a template string and replaces placeholders with corresponding values from the provided arguments. It supports numeric, named, and auto-indexed placeholders, as well as dynamic invocation of methods on values.
If a placeholder cannot resolve a value or an invoked method fails, the placeholder remains unchanged in the output.
Parameters:
- template (T ~string): A string containing placeholders enclosed in `{}`.
- args (...any): A variadic list of arguments, which may include:
- Positional arguments (numbers, strings, slices, structs, maps, etc.).
- A `Named` map for named placeholders.
Placeholder Forms:
- Numeric: `{1}`, `{2}` - References positional arguments by their 1-based index.
- Named: `{key}`, `{key.MethodName(param1, param2)}` - References keys from a `Named` map and allows method invocation.
- Fallback: `{key?fallback}` - Uses `fallback` if the key is not found in the named map.
- Auto-index: `{}` - Automatically uses the next positional argument if the placeholder is empty.
- Escaping: `{{` and `}}` - Emits literal braces, matching Rust formatting.
Returns:
- String: A formatted string with all resolved placeholders replaced by their corresponding values.
Notes:
- If a placeholder cannot resolve a value (e.g., missing key or out-of-range index), it remains unchanged in the output.
- Method invocation supports any type with accessible methods. If the method or its parameters are invalid, the value remains unmodified.
- Only a single `Named` map is used for named placeholders. If multiple `Named` maps are passed in args, the last one silently wins; merge them into one map beforehand if you need keys from several sources.
Security:
- Templates can invoke arbitrary exported methods on the supplied arguments via reflection (e.g. `{key.MethodName(...)}`). A template must therefore be treated as code: never pass untrusted or user-controlled input as the template string. Untrusted data is safe only as an argument VALUE (a positional argument or a `Named` map value), never as the template itself.
Usage:
// Example 1: Numeric placeholders
result := g.Format("{1} + {2} = {3}", 1, 2, 3)
// Example 2: Named placeholders
named := g.Named{
"name": "Alice",
"age": 30,
}
result := g.Format("My name is {name} and I am {age} years old.", named)
// Example 3: Method invocation on values
result := g.Format("Hex: {1.Hex}, Binary: {1.Binary}", g.Int(255))
// Example 4: Fallbacks and chaining
named := g.Named{
"name": g.String(" john "),
"city": g.String("New York"),
}
result := g.Format("Hello, {name.Trim.Title}. Welcome to {city?Unknown}!", named)
func (String) Builder ¶ added in v1.0.62
Builder returns a new Builder initialized with the content of the String.
func (String) BytesUnsafe ¶ added in v1.0.147
BytesUnsafe converts the String into Bytes without copying memory. Warning: the resulting Bytes shares the same underlying memory as the original String. If the original String is modified through unsafe operations (rare), or if it is garbage collected, the Bytes may become invalid or cause undefined behavior.
func (String) Center ¶
Center justifies the String by adding padding on both sides, up to the specified length. If the length of the String is already greater than or equal to the specified length, or the pad is empty, the original String is returned.
The padding String is repeated as necessary to evenly distribute the remaining length on both sides. The padding is added to the left and right of the String.
Parameters:
- length: The desired length of the resulting justified String.
- pad: The String used as padding.
Example usage:
s := g.String("Hello")
result := s.Center(10, "...")
// result: "..Hello..."
func (String) Chars ¶
Chars splits the String into individual UTF-8 characters and returns the iterator. It is the canonical way to iterate runes of a String, equivalent to s.Split("").
func (String) Chunks ¶
Chunks splits the String into chunks of the specified size.
This function iterates through the String, creating new String chunks of the specified size. If size is less than or equal to 0 or the String is empty, it returns an empty Slice[String]. If size is greater than or equal to the length of the String, it returns an Slice[String] containing the original String.
Parameters:
- size (Int): The size of the chunks to split the String into.
Returns:
- Slice[String]: A slice of String chunks of the specified size.
Example usage:
text := g.String("Hello, World!")
chunks := text.Chunks(4)
chunks contains {"Hell", "o, W", "orld", "!"}.
func (String) Clone ¶ added in v1.0.148
Clone returns a copy of the String. It ensures that the returned String does not share underlying memory with the original String, making it safe to modify or store independently.
func (String) Cmp ¶ added in v1.0.70
Cmp compares two Strings and returns an cmp.Ordering indicating their relative order. The result will be cmp.Equal if s==str, cmp.Less if s < str, and cmp.Greater if s > str.
func (String) Compress ¶ added in v1.0.85
func (s String) Compress() compress
Compress returns a compress struct wrapping the given String.
func (String) ContainsAll ¶
ContainsAll checks if the given String contains all the specified substrings.
func (String) ContainsAny ¶
ContainsAny checks if the String contains any of the specified substrings.
func (String) ContainsAnyChars ¶
ContainsAnyChars checks if the String contains any characters from the specified String.
func (String) ContainsRune ¶
ContainsRune checks if the String contains the specified rune.
func (String) Count ¶
Count returns the number of non-overlapping instances of the substring in the String.
func (String) Cut ¶
Cut returns two String values. The first String contains the remainder of the original String after the cut. The second String contains the text between the first occurrences of the 'start' and 'end' strings, with tags removed if specified.
The function searches for the 'start' and 'end' strings within the String. If both are found, it returns the first String containing the remainder of the original String after the cut, followed by the second String containing the text between the first occurrences of 'start' and 'end' with tags removed if specified.
If either 'start' or 'end' is empty or not found in the String, it returns the original String as the second String, and an empty String as the first.
Parameters:
- start (String): The String marking the beginning of the text to be cut.
- end (String): The String marking the end of the text to be cut.
- rmtags (bool, optional): An optional boolean parameter indicating whether to remove the matched region (including the 'start' and 'end' tags) from the remainder. Defaults to false, in which case the remainder equals the original String and only the cut content is extracted.
Returns:
String: The first String containing the remainder of the original String. When rmtags is true the matched region is removed from it; otherwise it is the original String. Returns an empty String if 'start' or 'end' is empty or not found.
String: The second String containing the text between the first occurrences of 'start' and 'end', or the original String if 'start' or 'end' is empty or not found.
Example usage:
s := g.String("Hello, [world]! How are you?")
remainder, cut := s.Cut("[", "]", true)
// remainder: "Hello, ! How are you?"
// cut: "world"
func (String) Decode ¶ added in v1.0.85
func (s String) Decode() decode
Decode returns a decode struct wrapping the given String.
func (String) Decompress ¶ added in v1.0.85
func (s String) Decompress() decompress
Decompress returns a decompress struct wrapping the given String.
func (String) Encode ¶ added in v1.0.85
func (s String) Encode() encode
Encode returns an encode struct wrapping the given String.
func (String) EndsWithAny ¶ added in v1.0.90
EndsWithAny checks if the String ends with any of the provided suffixes. The method accepts a variable number of arguments, allowing for checking against multiple suffixes at once. It iterates over the provided suffixes and uses the HasSuffix function from the strings package to check if the String ends with each suffix. The function returns true if the String ends with any of the suffixes, and false otherwise.
Example usage:
s := g.String("example.com")
if s.EndsWithAny(".com", ".net") {
// do something
}
func (String) Fields ¶
Fields splits the String into a slice of substrings, removing any whitespace, and returns the iterator.
func (String) FieldsBy ¶ added in v1.0.76
FieldsBy splits the String into a slice of substrings using a custom function to determine the field boundaries, and returns the iterator.
func (String) Gte ¶ added in v1.0.76
Gte checks if the String is greater than or equal to the specified String.
func (String) Hash ¶
func (s String) Hash() shash
Hash returns a shash struct wrapping the given String.
func (String) Index ¶
Index returns the index of the first instance of the specified substring in the String, or -1 if substr is not present in s.
func (String) IndexRune ¶
IndexRune returns the index of the first instance of the specified rune in the String.
func (String) IsLower ¶ added in v1.0.195
IsLower checks if the String consists only of lowercase letters.
func (String) IsUpper ¶ added in v1.0.195
IsUpper checks if the String consists only of uppercase letters.
func (String) LastIndex ¶
LastIndex returns the index of the last instance of the specified substring in the String, or -1 if substr is not present in s.
func (String) LeftJustify ¶
LeftJustify justifies the String to the left by adding padding to the right, up to the specified length. If the length of the String is already greater than or equal to the specified length, or the pad is empty, the original String is returned.
The padding String is repeated as necessary to fill the remaining length. The padding is added to the right of the String.
Parameters:
- length: The desired length of the resulting justified String.
- pad: The String used as padding.
Example usage:
s := g.String("Hello")
result := s.LeftJustify(10, "...")
// result: "Hello....."
func (String) Lte ¶ added in v1.0.76
Lte checks if the String is less than or equal to the specified String.
func (String) Map ¶
Map applies the provided function to all runes in the String and returns the resulting String.
func (String) NormalizeNFC ¶
NormalizeNFC returns a new String with its Unicode characters normalized using the NFC form.
func (String) Prepend ¶ added in v1.0.62
Prepend prepends the specified String to the current String.
func (String) Print ¶
Print writes the content of the String to the standard output (console) and returns the String unchanged.
func (String) Println ¶ added in v1.0.122
Println writes the content of the String to the standard output (console) with a newline and returns the String unchanged.
func (String) Random ¶
Random generates a random String of the specified length, selecting characters from predefined sets. If additional character sets are provided, only those will be used; the default set (ASCII_LETTERS and DIGITS) is excluded unless explicitly provided.
Parameters: - length (Int): Length of the random String to generate. - letters (...String): Additional character sets to consider for generating the random String (optional).
Returns: - String: Randomly generated String with the specified length.
If length is zero or negative, an empty String is returned. If an explicit letter set is provided but resolves to empty, an empty String is returned as well.
Example usage:
randomString := g.String("").Random(10)
randomString contains a random String with 10 characters.
func (String) Regexp ¶ added in v1.0.123
func (s String) Regexp() regexps
Regexp wraps a String into an re struct to provide regex-related methods.
func (String) Remove ¶ added in v1.0.78
Remove removes all occurrences of specified substrings from the String.
Parameters:
- matches ...String: Substrings to be removed from the string. Specify as many substrings as needed.
Returns:
- String: A new string with all specified substrings removed.
Example usage:
original := g.String("Hello, world! This is a test.")
modified := original.Remove(
"Hello",
"test",
)
// modified contains ", world! This is a ."
func (String) Repeat ¶
Repeat returns a new String consisting of the specified count of the original String.
func (String) Replace ¶
Replace replaces the 'oldS' String with the 'newS' String for the specified number of occurrences.
func (String) ReplaceAll ¶
ReplaceAll replaces all occurrences of the 'oldS' String with the 'newS' String.
func (String) ReplaceMulti ¶
ReplaceMulti creates a custom replacer to perform multiple string replacements.
Parameters:
- oldnew ...String: Pairs of strings to be replaced. Specify as many pairs as needed.
Returns:
- String: A new string with replacements applied using the custom replacer.
Example usage:
original := g.String("Hello, world! This is a test.")
replaced := original.ReplaceMulti(
"Hello", "Greetings",
"world", "universe",
"test", "example",
)
// replaced contains "Greetings, universe! This is an example."
func (String) ReplaceNth ¶
ReplaceNth returns a new String instance with the nth occurrence of oldS replaced with newS. If there aren't enough occurrences of oldS, the original String is returned. If n is less than -1, the original String is also returned. If n is -1, the last occurrence of oldS is replaced with newS.
Returns:
- A new String instance with the nth occurrence of oldS replaced with newS.
Example usage:
s := g.String("The quick brown dog jumped over the lazy dog.")
result := s.ReplaceNth("dog", "fox", 2)
fmt.Println(result)
Output: "The quick brown dog jumped over the lazy fox.".
func (String) RightJustify ¶
RightJustify justifies the String to the right by adding padding to the left, up to the specified length. If the length of the String is already greater than or equal to the specified length, or the pad is empty, the original String is returned.
The padding String is repeated as necessary to fill the remaining length. The padding is added to the left of the String.
Parameters:
- length: The desired length of the resulting justified String.
- pad: The String used as padding.
Example usage:
s := g.String("Hello")
result := s.RightJustify(10, "...")
// result: ".....Hello"
func (*String) Scan ¶ added in v1.0.198
Scan implements the database/sql.Scanner interface for g.String.
Behavior:
- If src is nil, the String is set to an empty string.
- If src is a string, it is directly assigned.
- If src is a []byte, it is converted to a string.
- Otherwise, an error is returned.
Supported SQL types (common):
- TEXT / VARCHAR → string
- BLOB / BYTEA → []byte (converted to string)
Notes:
- This method allows g.String to be used directly with database/sql and compatible drivers.
func (String) Similarity ¶
Similarity calculates the similarity between two Strings using the Levenshtein distance algorithm and returns the similarity percentage as an Float.
The function compares two Strings using the Levenshtein distance, which measures the difference between two sequences by counting the number of single-character edits required to change one sequence into the other. The similarity is then calculated by normalizing the distance by the maximum length of the two input Strings.
Parameters:
- str (String): The String to compare with s.
Returns:
- Float: The similarity percentage between the two Strings as a value between 0 and 100.
Example usage:
s1 := g.String("kitten")
s2 := g.String("sitting")
similarity := s1.Similarity(s2) // 57.14285714285714
func (String) Split ¶
Split splits the String by the specified separator and returns the iterator. If sep is empty, the String is split after each UTF-8 rune; Chars is the canonical way to iterate runes.
func (String) SplitAfter ¶ added in v1.0.76
SplitAfter splits the String after each instance of the specified separator and returns the iterator.
func (String) SplitN ¶
SplitN splits the String into substrings using the provided separator and returns an Slice[String] of the results. The n parameter controls the number of substrings to return: - If n is negative, there is no limit on the number of substrings returned. - If n is zero, an empty Slice[String] is returned. - If n is positive, at most n substrings are returned.
func (String) StartsWith ¶
StartsWith checks if the String starts with the specified prefix.
func (String) StartsWithAny ¶ added in v1.0.90
StartsWithAny checks if the String starts with any of the provided prefixes. The method accepts a variable number of arguments, allowing for checking against multiple prefixes at once. It iterates over the provided prefixes and uses the HasPrefix function from the strings package to check if the String starts with each prefix. The function returns true if the String starts with any of the prefixes, and false otherwise.
Example usage:
s := g.String("http://example.com")
if s.StartsWithAny("http://", "https://") {
// do something
}
func (String) StripPrefix ¶ added in v1.0.81
StripPrefix trims the specified prefix from the String.
func (String) StripSuffix ¶ added in v1.0.81
StripSuffix trims the specified suffix from the String.
func (String) SubString ¶ added in v1.0.127
SubString extracts a substring from the String starting at the 'start' index and ending before the 'end' index. The function also supports an optional 'step' parameter to define the increment between indices in the substring. If 'start' or 'end' index is negative, they represent positions relative to the end of the String: - A negative 'start' index indicates the position from the end of the String, moving backward. - A negative 'end' index indicates the position from the end of the String. The function ensures that indices are adjusted to fall within the valid range of the String's length. Out-of-bounds indices are clamped to the String's bounds instead of panicking; if 'start' exceeds 'end' (for a positive step) the result is an empty String.
func (String) Transform ¶ added in v1.0.89
Transform applies a transformation function to the String and returns the result.
func (String) TrimEndSet ¶ added in v1.0.82
TrimEndSet removes the specified set of characters from the end of the String.
func (String) TrimSet ¶ added in v1.0.82
TrimSet removes the specified set of characters from both the beginning and end of the String.
func (String) TrimStartSet ¶ added in v1.0.82
TrimStartSet removes the specified set of characters from the beginning of the String.
func (String) Truncate ¶ added in v1.0.126
Truncate shortens the String to the specified maximum length. If the String exceeds the specified length, it is truncated, and an ellipsis ("...") is appended to indicate the truncation.
If the length of the String is less than or equal to the specified maximum length, the original String is returned unchanged.
The method respects Unicode characters and truncates based on the number of runes, not bytes.
Parameters:
- max: The maximum number of runes allowed in the resulting String.
Returns:
- A new String truncated to the specified maximum length with "..." appended if truncation occurs. Otherwise, returns the original String.
Example usage:
s := g.String("Hello, World!")
result := s.Truncate(5)
// result: "Hello..."
s2 := g.String("Short")
result2 := s2.Truncate(10)
// result2: "Short"
s3 := g.String("😊😊😊😊😊")
result3 := s3.Truncate(3)
// result3: "😊😊😊..."
func (String) TryBigInt ¶ added in v1.0.205
TryBigInt attempts to convert the String receiver into a Result containing a *big.Int. This function assumes the string represents a numerical value, which can be in decimal, hexadecimal (prefixed with "0x"), or octal (prefixed with "0") format. The function leverages the SetString method of the math/big package, automatically detecting the numeric base when set to 0.
If the string is correctly formatted and represents a valid number, TryBigInt returns an Ok containing the *big.Int parsed from the string. If the string is empty, contains invalid characters, or does not conform to a recognizable numeric format, TryBigInt returns an Err describing the invalid input.
Returns:
- A Result[*big.Int] encapsulating the conversion result. It returns Ok[*big.Int] with the parsed value if successful, otherwise Err[*big.Int] if the parsing fails.
func (String) TryBool ¶ added in v1.0.228
TryBool tries to parse the String as a bool and returns the result. It accepts the values understood by strconv.ParseBool: 1, t, T, TRUE, true, True, 0, f, F, FALSE, false, False.
func (String) TryComplex ¶ added in v1.0.228
func (s String) TryComplex() Result[complex128]
TryComplex tries to parse the String as a complex number and returns a complex128.
func (String) TryFloat ¶ added in v1.0.205
TryFloat tries to parse the String as a float64 and returns an Float.
func (String) TryInt ¶ added in v1.0.205
TryInt tries to parse the String as an int and returns an Int.
type Unit ¶ added in v1.0.174
type Unit struct{}
Unit represents an empty value. Used in contexts where a function needs to return "something" but the actual value doesn't matter, only success/failure status.
type VacantEntry ¶ added in v1.0.200
type VacantEntry[K comparable, V any] struct { // contains filtered or unexported fields }
VacantEntry represents a view into a map entry that is known to be absent.
It is typically obtained from Map.Entry(key) when the key does not exist. VacantEntry allows inserting a value for the key in a controlled manner.
func (VacantEntry[K, V]) AndModify ¶ added in v1.0.200
func (e VacantEntry[K, V]) AndModify(fn func(*V)) Entry[K, V]
AndModify does nothing for VacantEntry and returns the entry unchanged.
Since there is no existing value to modify, the function is not called. This allows fluent chaining like Entry(k).AndModify(f).OrInsert(v) to work correctly regardless of whether the key exists.
func (VacantEntry[K, V]) Insert ¶ added in v1.0.200
func (e VacantEntry[K, V]) Insert(value V) V
Insert inserts the provided value into the map and returns it.
After this call, the key is present in the map with the given value.
func (VacantEntry[K, V]) Key ¶ added in v1.0.200
func (e VacantEntry[K, V]) Key() K
Key returns the key that would be used for insertion.
func (VacantEntry[K, V]) OrDefault ¶ added in v1.0.200
func (e VacantEntry[K, V]) OrDefault() V
OrDefault inserts the zero value of V into the map and returns it.
This is useful for types where the zero value is a valid initial state, such as numeric types (0), slices (nil), or structs with zero defaults.
func (VacantEntry[K, V]) OrInsert ¶ added in v1.0.200
func (e VacantEntry[K, V]) OrInsert(value V) V
OrInsert inserts the provided value and returns it.
This is the primary method for inserting values via VacantEntry.
func (VacantEntry[K, V]) OrInsertWith ¶ added in v1.0.200
func (e VacantEntry[K, V]) OrInsertWith(fn func() V) V
OrInsertWith inserts the value returned by the function and returns it.
The function is guaranteed to be called exactly once. Use this when computing the default value is expensive.
func (VacantEntry[K, V]) OrInsertWithKey ¶ added in v1.0.200
func (e VacantEntry[K, V]) OrInsertWithKey(fn func(K) V) V
OrInsertWithKey inserts the value returned by the function and returns it.
The function receives the entry key and is guaranteed to be called exactly once. Use this when the default value depends on the key.
type VacantOrdEntry ¶ added in v1.0.200
type VacantOrdEntry[K comparable, V any] struct { // contains filtered or unexported fields }
VacantOrdEntry represents a view into an ordered map entry that is known to be absent.
It is typically obtained from MapOrd.Entry(key) when the key does not exist. VacantOrdEntry allows inserting a new key-value pair into the ordered map.
func (VacantOrdEntry[K, V]) AndModify ¶ added in v1.0.200
func (e VacantOrdEntry[K, V]) AndModify(fn func(*V)) OrdEntry[K, V]
AndModify does nothing for VacantOrdEntry and returns the entry unchanged.
Since there is no existing value to modify, the function is not called. This allows fluent chaining like Entry(k).AndModify(f).OrInsert(v) to work correctly regardless of whether the key exists.
func (VacantOrdEntry[K, V]) Insert ¶ added in v1.0.200
func (e VacantOrdEntry[K, V]) Insert(value V) V
Insert inserts a new key-value pair into the ordered map and returns the value.
The new entry is appended to the end of the ordered map. After this call, the key is present in the map with the given value.
func (VacantOrdEntry[K, V]) Key ¶ added in v1.0.200
func (e VacantOrdEntry[K, V]) Key() K
Key returns the key that would be used for insertion.
func (VacantOrdEntry[K, V]) OrDefault ¶ added in v1.0.200
func (e VacantOrdEntry[K, V]) OrDefault() V
OrDefault inserts the zero value of V into the ordered map and returns it.
This is useful for types where the zero value is a valid initial state, such as numeric types (0), slices (nil), or structs with zero defaults.
func (VacantOrdEntry[K, V]) OrInsert ¶ added in v1.0.200
func (e VacantOrdEntry[K, V]) OrInsert(value V) V
OrInsert inserts the provided value and returns it.
This is the primary method for inserting values via VacantOrdEntry.
func (VacantOrdEntry[K, V]) OrInsertWith ¶ added in v1.0.200
func (e VacantOrdEntry[K, V]) OrInsertWith(fn func() V) V
OrInsertWith inserts the value returned by the function and returns it.
The function is guaranteed to be called exactly once. Use this when computing the default value is expensive.
func (VacantOrdEntry[K, V]) OrInsertWithKey ¶ added in v1.0.200
func (e VacantOrdEntry[K, V]) OrInsertWithKey(fn func(K) V) V
OrInsertWithKey inserts the value returned by the function and returns it.
The function receives the entry key and is guaranteed to be called exactly once. Use this when the default value depends on the key.
type VacantSafeEntry ¶ added in v1.0.200
type VacantSafeEntry[K comparable, V any] struct { // contains filtered or unexported fields }
VacantSafeEntry represents a view into a concurrent map entry that is known to be absent at the time of creation.
It is typically obtained from MapSafe.Entry(key) when the key does not exist. All operations on VacantSafeEntry are safe for concurrent use.
The modify field stores a pending modification function from AndModify, which will be applied if OrInsert loses a race with another goroutine.
func (VacantSafeEntry[K, V]) AndModify ¶ added in v1.0.200
func (e VacantSafeEntry[K, V]) AndModify(fn func(*V)) SafeEntry[K, V]
AndModify registers a modification function to be applied to the value.
If the key was concurrently inserted by another goroutine since this VacantSafeEntry was created, the modification is applied immediately via OccupiedSafeEntry.AndModify.
Otherwise, the function is stored and will be applied later by OrInsert if it loses the race to insert the key. This ensures that the pattern Entry(k).AndModify(f).OrInsert(v) correctly increments existing values even under heavy concurrent access.
Returns the appropriate SafeEntry for method chaining.
func (VacantSafeEntry[K, V]) Insert ¶ added in v1.0.200
func (e VacantSafeEntry[K, V]) Insert(value V) V
Insert inserts the provided value into the map and returns the stored value.
If another goroutine inserts the same key concurrently, the existing value is returned instead. Equivalent to OrInsert for VacantSafeEntry.
func (VacantSafeEntry[K, V]) Key ¶ added in v1.0.200
func (e VacantSafeEntry[K, V]) Key() K
Key returns the key that would be used for insertion.
func (VacantSafeEntry[K, V]) OrDefault ¶ added in v1.0.200
func (e VacantSafeEntry[K, V]) OrDefault() V
OrDefault inserts the zero value of V into the map and returns the stored value.
If another goroutine inserts the same key concurrently and a pending modification was registered via AndModify, it is applied atomically to the existing value before returning.
func (VacantSafeEntry[K, V]) OrInsert ¶ added in v1.0.200
func (e VacantSafeEntry[K, V]) OrInsert(value V) V
OrInsert inserts the provided value and returns the stored value.
If another goroutine inserts the same key concurrently (the insert "loses the race"), the existing value is used instead. In this case, if a pending modification was registered via AndModify, it is applied atomically to the existing value before returning.
This ensures that chained calls like Entry(k).AndModify(f).OrInsert(v) behave correctly under concurrent access: under contended insertion the modification is applied to the winning value.
Edge case: if the key is also removed by another goroutine between the lost insert and the modify, the modification has nothing to apply to and the pre-modify value observed during the failed insert is returned. In that narrow window the modification can be lost.
func (VacantSafeEntry[K, V]) OrInsertWith ¶ added in v1.0.200
func (e VacantSafeEntry[K, V]) OrInsertWith(fn func() V) V
OrInsertWith inserts the value returned by the function and returns the stored value.
Note: Due to lock-free implementation, fn() is evaluated before the atomic insertion. If another goroutine inserts the key concurrently, the result of fn() may be discarded and the existing value is returned instead.
func (VacantSafeEntry[K, V]) OrInsertWithKey ¶ added in v1.0.200
func (e VacantSafeEntry[K, V]) OrInsertWithKey(fn func(K) V) V
OrInsertWithKey inserts the value returned by the function and returns the stored value.
Note: Due to lock-free implementation, fn() is evaluated before the atomic insertion. If another goroutine inserts the key concurrently, the result of fn() may be discarded and the existing value is returned instead.
Source Files
¶
- bytes.go
- bytes_compdecomp.go
- bytes_encdec.go
- bytes_hash.go
- bytes_regexp.go
- bytes_text.go
- deque.go
- deque_iter.go
- dir.go
- doc.go
- entry.go
- entry_ordered.go
- entry_safe.go
- errors.go
- file.go
- file_encdec.go
- float.go
- float_math.go
- globals.go
- heap.go
- heap_iter.go
- int.go
- int_checked.go
- iter_shared.go
- map.go
- map_iter.go
- map_ordered.go
- map_ordered_iter.go
- map_safe.go
- mutex.go
- option.go
- option_json.go
- option_sql.go
- print.go
- print_fmt.go
- result.go
- result_iter.go
- result_json.go
- rwlock.go
- seq_pairs.go
- set.go
- set_iter.go
- slice.go
- slice_iter.go
- string.go
- string_builder.go
- string_compdecomp.go
- string_encdec.go
- string_hash.go
- string_regexp.go
Directories
¶
| Path | Synopsis |
|---|---|
|
Package cmp provides three-way comparison primitives (Ordering, Cmp, Reverse) used by the sorting, heap and min/max APIs of the g library.
|
Package cmp provides three-way comparison primitives (Ordering, Cmp, Reverse) used by the sorting, heap and min/max APIs of the g library. |
|
Package constraints defines generic type constraints (Signed, Unsigned, Integer, Float, ...) shared across the g library.
|
Package constraints defines generic type constraints (Signed, Unsigned, Integer, Float, ...) shared across the g library. |
|
Package dbg provides debugging helpers that print an expression together with its source file, line and enclosing function (dbg.Dbg, dbg.CallerInfo).
|
Package dbg provides debugging helpers that print an expression together with its source file, line and enclosing function (dbg.Dbg, dbg.CallerInfo). |
|
examples
|
|
|
bytes
command
|
|
|
bytes_float_conversions
command
|
|
|
bytes_int_conversions
command
|
|
|
cmp
command
|
|
|
deque
command
|
|
|
dirs/dirs_copy
command
|
|
|
dirs/dirs_creating
command
|
|
|
dirs/dirs_iter
command
|
|
|
dirs/dirs_walk
command
|
|
|
entry
command
|
|
|
files/file_encode_decode
command
|
|
|
files/file_guard
command
|
|
|
files/file_iter
command
|
|
|
files/files
command
|
|
|
files/stderr_to_file
command
|
|
|
files/tmp_file
command
|
|
|
floats
command
|
|
|
heap
command
|
|
|
ints
command
|
|
|
iter/iter_any
command
|
|
|
iter/iter_chain
command
|
|
|
iter/iter_chunk_by
command
|
|
|
iter/iter_chunks
command
|
|
|
iter/iter_combinations
command
|
|
|
iter/iter_contains
command
|
|
|
iter/iter_context
command
|
|
|
iter/iter_count
command
|
|
|
iter/iter_counter
command
|
|
|
iter/iter_dedup
command
|
|
|
iter/iter_deque_filtermap
command
|
|
|
iter/iter_deque_flatmap
command
|
|
|
iter/iter_deque_scan
command
|
|
|
iter/iter_enumerate
command
|
|
|
iter/iter_filter
command
|
|
|
iter/iter_filtermap
command
|
|
|
iter/iter_find
command
|
|
|
iter/iter_flatmap
command
|
|
|
iter/iter_flatten
command
|
|
|
iter/iter_fold
command
|
|
|
iter/iter_from_chan
command
|
|
|
iter/iter_heap_filtermap
command
|
|
|
iter/iter_heap_flatmap
command
|
|
|
iter/iter_heap_scan
command
|
|
|
iter/iter_inspect
command
|
|
|
iter/iter_intersperse
command
|
|
|
iter/iter_kotlin
command
|
|
|
iter/iter_map
command
|
|
|
iter/iter_map_filtermap
command
|
|
|
iter/iter_next
command
|
|
|
iter/iter_partition
command
|
|
|
iter/iter_permutations
command
|
|
|
iter/iter_range_for_map_set
command
|
|
|
iter/iter_scan
command
|
|
|
iter/iter_skip
command
|
|
|
iter/iter_sort
command
|
|
|
iter/iter_step
command
|
|
|
iter/iter_sumby
command
|
|
|
iter/iter_take
command
|
|
|
iter/iter_to_chan
command
|
|
|
iter/iter_trymap
command
|
|
|
iter/iter_unique
command
|
|
|
iter/iter_windows
command
|
|
|
iter/iter_zip
command
|
|
|
main
command
|
|
|
map
command
|
|
|
maps_ordered
command
|
|
|
mapsafe_entry_stress
command
|
|
|
monads/option
command
|
|
|
monads/option_json
command
|
|
|
monads/option_recover
command
|
|
|
monads/option_sql
command
|
|
|
monads/result
command
|
|
|
monads/result_err
command
|
|
|
monads/result_recover
command
|
|
|
mutex
command
|
|
|
pool/pool
command
|
|
|
pool/pool_cancel_on
command
|
|
|
pool/pool_cancel_on_error
command
|
|
|
pool/pool_context
command
|
|
|
pool/pool_metrics
command
|
|
|
pool/pool_perf
command
|
|
|
pool/rate/pool_rate
command
|
|
|
pool/rate/pool_rate_advanced
command
|
|
|
pool/std_vs_pool
command
|
|
|
pool/stream/pool
command
|
|
|
pool/stream/pool_and_iter
command
|
|
|
pool/stream/pool_cancel_on
command
|
|
|
pool/stream/pool_cancel_on_error
command
|
|
|
pool/stream/pool_context
command
|
|
|
pool/stream/pool_metrics
command
|
|
|
prime
command
|
|
|
print
command
|
|
|
print/basic
command
|
|
|
print/errorf
command
|
|
|
print/format
command
|
|
|
print/format_spec
command
|
|
|
range
command
|
|
|
rwlock
command
|
|
|
sets
command
|
|
|
slices/slice_funcs
command
|
|
|
slices/slice_of_slices
command
|
|
|
slices/slices
command
|
|
|
slices/slices_sort
command
|
|
|
slices/slices_unpack
command
|
|
|
strings
command
|
|
|
strings_builder
command
|
|
|
strings_regexp
command
|
|
|
unsafe_slice_converter
command
|
|
|
unsafe_string_bytes
command
|
|
|
Package f provides predicate helpers and combinators (f.Eq, f.Gt, f.Contains, ...) for use with iterator methods such as Filter and Exclude.
|
Package f provides predicate helpers and combinators (f.Eq, f.Gt, f.Contains, ...) for use with iterator methods such as Filter and Exclude. |
|
internal
|
|
|
filelock
Package filelock provides a platform-independent API for advisory file locking.
|
Package filelock provides a platform-independent API for advisory file locking. |
|
filelock/syscall/windows/sysdll
Package sysdll is an internal leaf package that records and reports which Windows DLL names are used by Go itself.
|
Package sysdll is an internal leaf package that records and reports which Windows DLL names are used by Go itself. |
|
Package pool provides a generic goroutine pool with concurrency limits, rate limiting, cancellation and Result-based error collection, in Wait and Stream modes.
|
Package pool provides a generic goroutine pool with concurrency limits, rate limiting, cancellation and Result-based error collection, in Wait and Stream modes. |
|
Package ref provides a utility function for creating a pointer to a value.
|
Package ref provides a utility function for creating a pointer to a value. |