g

package module
v1.1.1 Latest Latest
Warning

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

Go to latest
Published: Aug 10, 2026 License: MIT Imports: 46 Imported by: 70

README

g - Functional programming framework for Go.

Go Reference Coverage Status Go Mentioned in Awesome Go Ask DeepWiki

go get github.com/enetx/g

Requires Go 1.27+ (generic methods: Map, Then, Fold, Zip and friends change element types right in the chain — no more package-level Transform* workarounds).

Designed to be cheap to compile: the type graph is deliberately de-welded, so a package that only uses g.String compiles ~1.5k functions instead of ~33k, and heavyweight areas (filesystem, regex) live in subpackages (g/fs, g/rx). The only non-stdlib dependency is golang.org/x/text.


Quick Start

package main

import (
    "fmt"
    "github.com/enetx/g"
)

func main() {
    // Slice with functional operations
    g.SliceOf(1, 2, 3, 4, 5).
        Iter().
        Filter(func(x int) bool { return x%2 == 0 }).
        Map(func(x int) int { return x * x }).
        Collect().
        Slice().
        Println() // Slice[4, 16]

    // Safe map access with Option
    m := g.NewMap[string, int]()
    m.Insert("key", 42)

    value := m.Get("key").UnwrapOr(0)
    fmt.Println(value) // 42

    // Result for error handling
    result := g.String("123").TryInt()
    if result.IsOk() {
        fmt.Println(result.Unwrap()) // 123
    }
}

Navigation

Core Collections Sync Types
Option Slice Mutex String
Result Map RwLock Int/Float
Iterators Set Pool Bytes
Deque Regex (g/rx)
Heap File/Dir (g/fs)

Option

Safe nullable values: Some(value) or None.

opt := g.Some(42)           // Some(42)
none := g.None[int]()       // None

opt.IsSome()                // true
opt.Unwrap()                // 42 (panics if None)
opt.UnwrapOr(0)             // 42 (returns default if None)
opt.UnwrapOrDefault()       // 42 (returns zero value if None)

// From map lookup
v, ok := myMap[key]
opt := g.OptionOf(v, ok)

// Chaining
g.Some(5).Then(func(x int) g.Option[int] {
    return g.Some(x * 2)
}) // Some(10)
All Option Methods
Method Description
IsSome() / IsNone() Presence checks
IsSomeAnd(pred) / IsNoneOr(pred) Presence combined with a predicate
Some() Returns value (zero value if None — check first)
Unwrap() / Expect(msg) Returns value, panics if None
UnwrapOr(default) / UnwrapOrDefault() Returns value or fallback
Map(fn) Transforms the value, may change its type
MapOr(def, fn) / MapOrElse(defFn, fn) Map or fall back to a default
Then(fn) Chains a fallible transformation (and_then)
Filter(pred) Returns None if predicate fails
Or(other) / OrElse(fn) Fallback Option
Inspect(fn) Side effect on Some, returns self
g.OkOr(opt, err) / g.OkOrElse(opt, fn) Converts to Result (free functions)
Take() / Replace(v) / Insert(v) In-place mutation
Option() Returns (value, bool)

JSON: Some(v) ⇄ value, None ⇄ null (encoding/json/v2 native, v1 compatible).


Result

Success (Ok) or failure (Err) with error.

ok := g.Ok(42)                              // Ok(42)
err := g.Err[int](errors.New("failed"))     // Err

ok.IsOk()                   // true
ok.Unwrap()                 // 42
err.UnwrapOr(0)             // 0

// From standard (value, error) pattern
result := g.ResultOf(strconv.Atoi("42"))    // Ok(42)
result := g.String("42").TryInt()           // Ok(42)

// Chaining
g.Ok(10).Then(func(x int) g.Result[int] {
    return g.Ok(x * 2)
}) // Ok(20)

// Convert to Option (discards error)
opt := result.Option()      // Some(42)
All Result Methods
Method Description
IsOk() / IsErr() State checks
IsOkAnd(pred) / IsErrAnd(pred) State combined with a predicate
Ok() / Err() Returns value / error (zero if the other state)
Unwrap() / Expect(msg) Returns value, panics if Err
UnwrapErr() Returns error, panics if Ok
UnwrapOr(default) / UnwrapOrDefault() Returns value or fallback
Map(fn) Transforms the value, may change its type
MapOr(def, fn) / MapOrElse(defFn, fn) Map or fall back
Then(fn) / ThenOf(fn) Chains Result / (T, error) functions
Or(other) / OrElse(fn) Fallback Result
MapErr(fn) / Wrap(err) Transforms / wraps the error
Inspect(fn) / InspectErr(fn) Side effects, return self
ErrIs(target) / ErrAs(target) errors.Is / errors.As integration
Option() / Result() Converts to Option / (value, error)

JSON: Ok(v) ⇄ {"ok": v}, Err(e) ⇄ {"err": "msg"} (externally tagged; duplicate keys rejected).


Slice

Extended slice with 90+ methods.

s := g.SliceOf(1, 2, 3, 4, 5)
s := g.NewSlice[int](0, 10)     // empty, with capacity 10 (one arg sets len AND cap)

s.Len()                         // Int(5)
s.Get(0)                        // Some(1)
s.Get(100)                      // None (safe!)
s.Last()                        // Some(5)
s.Contains(3)                   // true

s.Push(6, 7)                    // append in place
s.Pop()                         // Some(7)
s.Clone()                       // safe copy

// Sorting
s.SortBy(cmp.Cmp)               // ascending
s.Reverse()                     // in place
rand.Shuffle(s)                 // random order (g/rand)
All Slice Methods
Category Methods
Access Get, Last, First
Modify Set, Push, Pop, Insert, Remove
Search Contains, ContainsBy, Index, IndexBy
Transform Clone, Reverse, SortBy, SubSlice
Convert Iter, Std
Info Len, Cap, IsEmpty

Map

Extended map with Entry API.

m := g.NewMap[string, int]()
// or from pairs: g.MapOf(g.Pair[string, int]{"a", 1}, g.Pair[string, int]{"b", 2})

m.Insert("a", 1)                // insert value
m.Get("a")                      // Some(1)
m.Get("x")                      // None
m.Contains("a")                 // true
m.Remove("a")                   // remove

m.Keys()                        // Slice of keys
m.Values()                      // Slice of values
Entry API

Efficient update without multiple lookups:

// Insert if absent
m.Entry("counter").OrInsert(0)

// Update if present, insert if absent
m.Entry("counter").AndModify(func(v *int) { *v++ }).OrInsert(1)

// Lazy initialization
m.Entry("key").OrInsertWith(func() int {
    return expensiveComputation()
})

Word frequency example:

words := g.SliceOf("apple", "banana", "apple", "cherry", "banana", "apple")
freq := g.NewMap[string, int]()

for _, word := range words {
    freq.Entry(word).AndModify(func(v *int) { *v++ }).OrInsert(1)
}
// {"apple": 3, "banana": 2, "cherry": 1}
Entry Pattern Matching
switch e := m.Entry("key").(type) {
case g.OccupiedEntry[string, int]:
    fmt.Println("Exists:", e.Get())
    e.Insert(newValue)      // replace
    e.Remove()              // delete
case g.VacantEntry[string, int]:
    e.Insert(defaultValue)  // insert
}

Set

Collection of unique elements.

s := g.SetOf(1, 2, 3)
s.Insert(4)                     // add
s.Remove(1)                     // remove
s.Contains(2)                   // true

// Set algebra (eager, returns Set)
s.Union(other)                  // A ∪ B
s.Intersection(other)           // A ∩ B
s.Difference(other)             // A \ B
s.SymmetricDifference(other)    // A △ B
s.Disjoint(other)               // no common elements?
Set Operations
a := g.SetOf(1, 2, 3, 4)
b := g.SetOf(3, 4, 5, 6)

a.Union(b)                      // Set{1, 2, 3, 4, 5, 6}
a.Intersection(b)               // Set{3, 4}
a.Difference(b)                 // Set{1, 2}
a.SymmetricDifference(b)        // Set{1, 2, 5, 6}

a.Subset(b)                     // false
a.Superset(b)                   // false

Heap

Priority queue (binary heap).

import "github.com/enetx/g/cmp"

// Min-heap (smallest first)
h := g.NewHeap(cmp.Cmp[int])
h.Push(5, 3, 8, 1, 9)
// or in one go: g.HeapOf(cmp.Cmp[int], 5, 3, 8, 1, 9)

h.Peek()                        // Some(1)
h.Pop()                         // Some(1)
h.Pop()                         // Some(3)

// Max-heap (largest first)
maxH := g.NewHeap(func(a, b int) cmp.Ordering {
    return cmp.Cmp(b, a)
})

// From a slice — spread into the variadic constructor
s := g.SliceOf(5, 3, 8, 1)
heap := g.HeapOf(cmp.Cmp[int], s...)

Deque

Double-ended queue (ring buffer). O(1) at both ends.

dq := g.NewDeque[int]()
dq := g.DequeOf(1, 2, 3)

dq.PushFront(0)                 // add to front
dq.PushBack(4)                  // add to back

dq.Front()                      // Some(0)
dq.Back()                       // Some(4)

dq.PopFront()                   // Some(0)
dq.PopBack()                    // Some(4)

dq.Get(1)                       // element at index
dq.Len()                        // length
dq.IsEmpty()                    // true/false

Iterators

Functional operations on sequences.

g.SliceOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10).
    Iter().
    Filter(func(x int) bool { return x%2 == 0 }).
    Map(func(x int) int { return x * x }).
    Take(3).
    Collect().
    Slice()
// Slice[4, 16, 36]

Thanks to generic methods (Go 1.27+), transformations can change the element type right in the chain:

g.SliceOf(1, 2, 3).
    Iter().
    Map(func(x int) g.String { return g.Int(x).String() }). // Seq[int] -> Seq[g.String]
    Collect().
    Slice().
    Join(", ").
    Println() // 1, 2, 3

// Fold into any accumulator type
words := g.SliceOf[g.String]("a", "bb", "ccc")
total := words.Iter().Fold(g.Int(0), func(acc g.Int, w g.String) g.Int { return acc + w.Len() })
// 6

// Typed Zip — pairs keep their real types
nums := g.SliceOf(1, 2, 3)
names := g.SliceOf("one", "two", "three")
nums.Iter().Zip(names.Iter()).ForEach(func(n int, s string) {
    fmt.Println(n, s)
})
Collecting

Collect() returns a collector; pick the container to materialize into. Set, Map, MapOrd and MapSafe take explicit type arguments — a method of Seq[V any] cannot constrain V to comparable, so the constraint lives on the collector method and the type is spelled at the call site:

s.Iter().Filter(fn).Collect().Slice()          // Slice[int]
s.Iter().Filter(fn).Collect().Set[int]()       // Set[int]
s.Iter().Collect().Deque()                     // *Deque[int]
s.Iter().Collect().Heap(cmp.Cmp)               // *Heap[int]

m.Iter().FilterByKey(fn).Collect().Pairs()               // []Pair[K, V]
m.Iter().FilterByKey(fn).Collect().Map[string, int]()    // Map[string, int]
m.Iter().Collect().MapOrd[string, int]()                 // MapOrd[string, int]
m.Iter().Collect().MapSafe[string, int]()                // *MapSafe[string, int]

Note: Collect() alone is lazy — nothing runs until a materializer is called.

Common Patterns
// Chain iterators
g.SliceOf(1, 2).Iter().Chain(g.SliceOf(3, 4).Iter()).Collect().Slice()
// Slice[1, 2, 3, 4]

// Sum with Fold
g.SliceOf(1, 2, 3, 4, 5).Iter().Fold(0, func(acc, x int) int { return acc + x })
// 15

// Enumerate
g.SliceOf("a", "b", "c").Iter().Enumerate().ForEach(func(i g.Int, v string) {
    fmt.Printf("%d: %s\n", i, v)
})

// Using f package predicates
import "github.com/enetx/g/f"

g.SliceOf(1, 2, 3, 4, 5).Iter().Filter(f.Ne(3)).Collect().Slice() // Slice[1, 2, 4, 5]
g.SliceOf("", "a", "").Iter().Exclude(f.IsZero).Collect().Slice()  // Slice["a"]
All Iterator Methods
Transform Slice Combine Aggregate Search Other
Map Take Chain Collect Find ForEach
Filter Skip Zip Fold Any Inspect
Exclude StepBy Enumerate Reduce All Range
FilterMap First Intersperse Count MaxBy Scan
FlatMap Last Cycle CounterBy MinBy Combinations
Flatten Nth Partition Permutations
Dedup Chunks ChunkBy Context
Unique Windows Chan
SortBy TakeWhile
SkipWhile

Mutex

Typed mutex — data bound to lock.

counter := g.NewMutex(0)

// Lock and modify
guard := counter.Lock()
guard.Set(guard.Get() + 1)
guard.Unlock()

// With defer (recommended)
func increment(c *g.Mutex[int]) {
    guard := c.Lock()
    defer guard.Unlock()
    guard.Set(guard.Get() + 1)
}

// Direct pointer access
guard := counter.Lock()
defer guard.Unlock()
*guard.Deref() += 1

// Non-blocking
if opt := counter.TryLock(); opt.IsSome() {
    guard := opt.Unwrap()
    defer guard.Unlock()
    // got the lock
}

Why typed mutex?

// Traditional — easy to forget locking
type Old struct {
    mu   sync.Mutex
    data map[string]int  // what protects this?
}

// Typed — impossible to access without lock
type New struct {
    data *g.Mutex[g.Map[string, int]]
}

func (s *New) Get(key string) g.Option[int] {
    guard := s.data.Lock()
    defer guard.Unlock()
    return guard.Deref().Get(key)
}

RwLock

Multiple readers OR single writer.

config := g.NewRwLock(Config{Port: 8080})

// Read (concurrent)
func getPort(c *g.RwLock[Config]) int {
    guard := c.Read()
    defer guard.Unlock()
    return guard.Get().Port
}

// Write (exclusive)
func setPort(c *g.RwLock[Config], port int) {
    guard := c.Write()
    defer guard.Unlock()
    guard.Deref().Port = port
}

// Non-blocking
if opt := config.TryRead(); opt.IsSome() { ... }
if opt := config.TryWrite(); opt.IsSome() { ... }
Use Case Choose
Read-heavy (config, cache) RwLock
Write-heavy or balanced Mutex
Simple counters Mutex

Pool

Goroutine pool for parallel tasks.

import "github.com/enetx/g/pool"

p := pool.New[int]().Limit(4)

for i := range 10 {
    p.Go(func() g.Result[int] {
        return g.Ok(i * 2)
    })
}

for result := range p.Wait() {
    if result.IsOk() {
        fmt.Println(result.Unwrap())
    }
}
With Context and Cancel on Error
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()

p := pool.New[int]().
    Context(ctx).
    CancelOnError().
    Limit(4)

for i := range 100 {
    p.Go(func() g.Result[int] {
        if i == 50 {
            return g.Err[int](errors.New("error"))
        }
        return g.Ok(i)
    })
}

for result := range p.Wait() {
    // stops after first error
}

String

Extended string with 80+ methods.

s := g.String("Hello, World!")

s.Len()                         // 13
s.Upper()                       // "HELLO, WORLD!"
s.Lower()                       // "hello, world!"
s.Contains("World")             // true
s.Trim()                        // remove whitespace

// Splitters return a plain []String — index, len and range work directly
parts := s.Split(", ")          // []String{"Hello", "World!"}
parts[0]                        // "Hello"

for _, part := range s.Split(", ") {
    part.Println()              // Hello / World!
}

// For chains, lift the slice into an iterator
g.SliceOf(s.Split(", ")...).Iter().Map(g.String.Upper).Collect().Slice()

// Conversions
s.Std()                         // Go string
s.Bytes()                       // Bytes type
g.String("42").TryInt()         // Result[Int]

// Encoding
s.Hash().MD5()                  // hash
s.Encode().Base64()             // encode
s.Compress().Gzip()             // compress
Randomness — g/rand

All randomness lives in one package (math/rand/v2 under the hood; the Secure* helpers draw from crypto/rand):

import "github.com/enetx/g/rand"

rand.N(10)                    // [0, 10)
rand.Range(5, 10)             // half-open [5, 10)
rand.RangeInclusive(1, 6)     // closed [1, 6]
rand.Float()                  // [0, 1)
rand.Chance(0.25)             // true with probability 0.25
rand.String(10)               // 10 alphanumeric characters
rand.SecureString(32)         // crypto/rand-backed token (keys, codes)
rand.SecureBytes(16)          // crypto/rand-backed raw bytes
rand.String(6, g.Digits)      // 6-digit code

users := g.SliceOf("ann", "bob", "eve")
rand.Choice(users)            // Option[string]
rand.Sample(users, 2)         // 2 distinct elements
rand.Shuffle(users)           // in place; accepts Slice, MapOrd, plain slices

The container types deliberately carry no random methods — one way to do it.

Regular expressions — g/rx

Compile a pattern once, then run it anywhere — patterns live in their own package:

import "github.com/enetx/g/rx"

re := rx.New(`[0-9]{4}-[0-9]{2}-[0-9]{2}`).Unwrap()

re.IsMatch("2026-08-09")                   // true
re.Find("on 2026-08-09 at noon")           // Option[String]
re.FindIter(hay).Take(2).Collect().Slice() // first two matches
re.Replace(s, "$1")                        // FIRST match only
re.ReplaceBy(s, fn)                        // FIRST match through a function
re.ReplaceAll(s, "$1")                     // every match

digits := rx.New(`[0-9]`).Unwrap()
digits.Split("a1b2c3").Collect().Slice()   // Slice[a, b, c]

// Bytes haystacks: IsMatchBytes, FindBytes, FindIterBytes, ...

Int / Float

Numeric types with utility methods.

i := g.Int(42)

i.Add(8)                        // 50
i.Mul(2)                        // 84
i.Abs()                         // absolute value
i.Min(10, 20)                   // minimum
i.Max(10, 20)                   // maximum

i.IsZero()                      // false
i.IsPositive()                  // true
i.IsNegative()                  // false

i.Binary()                      // binary string
i.Hex()                         // hex string

// Checked arithmetic — overflow becomes None instead of a silent wraparound
g.Int(math.MaxInt).CheckedAdd(1)   // None
g.Int(10).CheckedDiv(0)            // None — no division panic
g.Int(2).CheckedPow(62)            // Some(4611686018427387904)

// Saturating / Overflowing variants
g.Int(math.MaxInt).SaturatingAdd(1)   // MaxInt (clamped)
v, overflowed := g.Int(math.MaxInt).OverflowingAdd(1) // MinInt, true

// Float
f := g.Float(3.14159)
f.Round()                       // Int(3)
f.RoundDecimal(2)               // Float(3.14)
f.Sqrt()                        // square root

// Float math & classification
g.Float(1).Div(0).IsInf()       // true
g.Float(-3.75).Fract()          // -0.75
g.Float(2.5).Clamp(0, 2)        // 2
g.Float(math.Pi).ToDegrees()    // 180
g.Float(0.1).MulAdd(10, -1)     // true FMA — single rounding
// plus Exp/Ln/Log2/Log10, Sin..Atanh, Signum, Copysign, Hypot, Cbrt...

// Compare
i.Cmp(g.Int(50))                // cmp.Less

Bytes

Extended byte slice.

b := g.Bytes([]byte("Hello"))

b.Len()
b.Upper()
b.Lower()
b.Contains([]byte("ell"))

b.String()                      // to String
b.Std()                         // to []byte

File / Directory

Filesystem types live in the g/fs subpackage, so only programs that touch files pay for them:

import "github.com/enetx/g/fs"
File
// Read/Write
content := fs.NewFile("config.json").Read()      // Result[String]
fs.NewFile("output.txt").Write("Hello")
fs.NewFile("log.txt").Append("line\n")

// Open a new file with the specified name "text.txt" and process it line by line.
fs.NewFile("text.txt").
	Lines().                            // Reads the file line by line.
	Skip(2).                            // Skips the first 2 lines in the iterator.
	Exclude(f.IsZero).                  // Excludes lines that are empty or contain only whitespaces.
	Dedup().                            // Removes consecutive duplicate lines.
	Map(g.String.Upper).                // Converts each line to uppercase.
	Range(func(s g.Result[g.String]) bool { // Iterates over the lines while a condition is true.
		if s.IsErr() { // Handles any errors encountered while reading lines.
			fmt.Println("Error:", s.Err())
			return false // Stops the iteration if an error occurs.
		}

		if s.Ok().Contains("COULD") { // Checks if the line contains the substring "COULD".
			return false // Stops the iteration if the condition is met.
		}

		fmt.Println(s.Ok()) // Prints the line.
		return true         // Continues the iteration.
	})

// Properties
file := fs.NewFile("test.txt")
file.Exists()                   // check existence
file.Stat()                     // file info
file.Copy("backup.txt")         // copy
file.Rename("new.txt")          // rename
file.Remove()                   // delete
File Guard (Exclusive Lock)
locked := fs.NewFile("data.txt").Guard()  // holds exclusive lock
locked.Write("exclusive data")
locked.Close()                            // release lock
Directory
fs.NewDir("mydir").Create()
fs.NewDir("path/to/deep").CreateAll()

// Read contents
for file := range fs.NewDir(".").Read() {
    if file.IsOk() {
        file.Ok().Name().Println()
    }
}

// Recursively walk through the directory tree starting from the current directory
fs.NewDir(".").Walk().
	// Exclude directories and symlinked directories
	Exclude(func(f *fs.File) bool { return f.IsDir() && f.Dir().Ok().IsLink() }).
	// Exclude file symlinks
	Exclude((*fs.File).IsLink).
	// Process each walk result
	ForEach(func(v g.Result[*fs.File]) {
		if v.IsOk() {
			// Print the path of the file if no error occurred
			v.Ok().Path().Ok().Println()
		}
	})

// Iterate over and print the names of files in the current directory with a *.go extension
fs.NewDir("*.go").Glob().ForEach(func(f g.Result[*fs.File]) { f.Ok().Name().Println() })

// Copy the contents of the current directory to a new directory named "copy".
fs.NewDir(".").Copy("copy").Unwrap()

Formatting and Print

Placeholders support automatic, positional, and named values:

g.Format("{} {2} {name}", "auto", "positional", g.Named{"name": "named"})
g.Format("{{{name}}}", g.Named{"name": "value"}) // {value}

Dotted placeholders access DATA — struct fields, map keys, slice indices — never methods (transform values before formatting):

g.Format("{1.Field}", structVal)          // struct field
g.Format("{.outer.inner}", nestedMap)     // map keys
g.Format("{.1.2}", nestedSlice)           // slice indices

Format specs include alignment, width, precision, signs, alternate prefixes, and common representations:

g.Format("{:d} {:c} {:q} {:U} {:#010x}", 42, 65, "go\n", 'A', 255)

Use FormatTo to append to a reusable builder. TryFormat validates templates and returns Result[String]; TryFormatTo appends only when formatting succeeds.

Types can implement custom specs without reflection:

type Price float64

func (p Price) FormatValue(spec g.String) g.String {
    if spec == "currency" {
        return g.String(fmt.Sprintf("$%.2f", p))
    }
    return g.String(fmt.Sprintf("%.2f", p))
}

g.Format("{:currency}", Price(19.95)) // $19.95

Other Maps

MapOrd — Ordered Map

Maintains insertion order.

m := g.NewMapOrd[string, int]()
m.Insert("c", 3)
m.Insert("a", 1)
m.Insert("b", 2)

for k, v := range m.Iter() {
    fmt.Println(k, v)  // c, a, b order
}

m.SortByKey(cmp.Cmp)            // sort by key
m.SortByValue(cmp.Cmp)          // sort by value
MapSafe — Concurrent Map

Thread-safe for concurrent access.

m := g.NewMapSafe[string, int]()

// Safe from multiple goroutines
go func() { m.Insert("a", 1) }()
go func() { m.Get("a") }()

License

MIT License

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 an Iter method returning lazy sequences (Heap additionally offers a draining IntoIter) — Seq for values, Seq2 for key-value pairs, SeqSlices for grouped windows/chunks and SeqResult for fallible streams — built on g's own dependency-free iterator core. 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() // 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, zlib, flate) and Hash (MD5, SHA1, SHA256, SHA512).

Subpackages

  • fs: File and Dir — chainable, Result-based file and directory operations, including lazy line/chunk iterators over file contents.
  • rx: compiled regular expressions with a compile-once, rich matching API.
  • rand: all randomness (numbers, choices, samples, shuffles, strings) in one place.
  • 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 placeholders resolve data only: each dot-segment selects a map key, a MapOrd key, a slice/array index or a struct field — placeholders cannot invoke methods. Note that an untrusted template string can still choose which of the supplied argument data is printed.

Index

Constants

View Source
const (
	// ASCIILetters is the set of all ASCII letters (lowercase + uppercase).
	ASCIILetters String = ASCIILowercase + ASCIIUppercase
	// ASCIILowercase is the set of lowercase ASCII letters.
	ASCIILowercase String = "abcdefghijklmnopqrstuvwxyz"
	// ASCIIUppercase is the set of uppercase ASCII letters.
	ASCIIUppercase 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

View Source
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

func Errorf[T ~string](format T, args ...any) error

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

func FormatTo added in v1.0.228

func FormatTo[T ~string](builder *Builder, template T, args ...any)

FormatTo formats template and appends the result to builder without resetting it. It is intended for allocation-sensitive code that reuses a Builder across calls.

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) Cap added in v1.0.62

func (b *Builder) Cap() Int

Cap returns the builder’s current capacity.

func (*Builder) Grow added in v1.0.62

func (b *Builder) Grow(n Int)

Grow increases the builder’s capacity by at least n bytes.

func (*Builder) Len added in v1.0.62

func (b *Builder) Len() Int

Len returns the number of bytes currently in the 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

func (b *Builder) String() String

String returns the accumulated string as a custom String type.

func (*Builder) Write added in v1.0.62

func (b *Builder) Write(bs []byte) (int, error)

Write appends the given byte slice to the builder.

func (*Builder) WriteByte added in v1.0.62

func (b *Builder) WriteByte(c byte) error

WriteByte appends the given byte to the builder.

func (*Builder) WriteRune added in v1.0.62

func (b *Builder) WriteRune(r rune) (int, error)

WriteRune appends the given rune to the builder.

func (*Builder) WriteString added in v1.0.124

func (b *Builder) WriteString(str String) (int, error)

WriteString appends the given String to the builder.

type Bytes

type Bytes []byte

Bytes is a wrapper around the []byte type.

func NewBytes

func NewBytes[T ~string | ~[]byte](b T) Bytes

NewBytes creates a Bytes from the provided string or byte slice, mirroring NewString. For an empty pre-sized buffer use make(Bytes, n) or make(Bytes, n, cap) directly.

func (Bytes) Append added in v1.0.164

func (bs Bytes) Append(obs Bytes) Bytes

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

func (bs Bytes) Center(length Int, pad Bytes) Bytes

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

func (bs Bytes) Chars() []Bytes

Chars splits the Bytes into individual UTF-8 characters, equivalent to bs.Split(Bytes("")) and mirroring String.Chars.

func (Bytes) Chunks added in v1.0.228

func (bs Bytes) Chunks(size Int) []Bytes

Chunks splits the Bytes into chunks of the specified size.

This function iterates through the Bytes, creating chunks of the specified size. If size is less than or equal to 0 or the Bytes is empty, it returns nil. If size is greater than or equal to the length of the Bytes, it returns the original Bytes as the only chunk.

Unlike String.Chunks, which counts runes, the chunk size is measured in bytes, so multibyte UTF-8 sequences may be split across chunks.

The returned 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:

- []Bytes: the chunks of the specified size.

Example usage:

bs := g.Bytes("Hello, World!")
chunks := bs.Chunks(4)

chunks contains {"Hell", "o, W", "orld", "!"}.

func (Bytes) Clone

func (bs Bytes) Clone() Bytes

Clone creates a new Bytes instance with the same content as the current Bytes.

func (Bytes) Cmp added in v1.0.70

func (bs Bytes) Cmp(obs Bytes) cmp.Ordering

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) Contains

func (bs Bytes) Contains(obs Bytes) bool

Contains checks if the Bytes contains the specified Bytes.

func (Bytes) ContainsAll

func (bs Bytes) ContainsAll(obss ...Bytes) bool

ContainsAll checks if the Bytes contains all of the specified Bytes.

func (Bytes) ContainsAny

func (bs Bytes) ContainsAny(obss ...Bytes) bool

ContainsAny checks if the Bytes contains any of the specified Bytes.

func (Bytes) ContainsAnyChars

func (bs Bytes) ContainsAnyChars(chars String) bool

ContainsAnyChars checks if the given Bytes contains any characters from the input String.

func (Bytes) ContainsRune

func (bs Bytes) ContainsRune(r rune) bool

ContainsRune checks if the Bytes contains the specified rune.

func (Bytes) Count

func (bs Bytes) Count(obs Bytes) Int

Count counts the number of occurrences of the specified Bytes in the Bytes.

func (Bytes) Cut added in v1.0.228

func (bs Bytes) Cut(start, end Bytes, rmtags ...bool) (Bytes, Bytes)

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

func (bs Bytes) EndsWith(suffix Bytes) bool

EndsWith checks if the Bytes ends with the specified suffix.

func (Bytes) EndsWithAny added in v1.0.225

func (bs Bytes) EndsWithAny(suffixes ...Bytes) bool

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) Eq

func (bs Bytes) Eq(obs Bytes) bool

Eq checks if the Bytes is equal to another Bytes.

func (Bytes) EqFold

func (bs Bytes) EqFold(obs Bytes) bool

EqFold compares two Bytes slices case-insensitively.

func (Bytes) Fields added in v1.0.77

func (bs Bytes) Fields() []Bytes

Fields splits the Bytes around whitespace. See String.Lines for why the return type is a plain slice.

func (Bytes) FieldsBy added in v1.0.77

func (bs Bytes) FieldsBy(fn func(r rune) bool) []Bytes

FieldsBy splits the Bytes using a custom function to determine the field boundaries. See String.Lines for why the return type is a plain slice.

func (Bytes) FloatBE added in v1.0.180

func (bs Bytes) FloatBE() Float

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

func (bs Bytes) FloatLE() Float

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) Gt

func (bs Bytes) Gt(obs Bytes) bool

Gt checks if the Bytes is greater than another Bytes.

func (Bytes) Gte added in v1.0.225

func (bs Bytes) Gte(obs Bytes) bool

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

func (bs Bytes) Index(obs Bytes) Int

Index returns the index of the first instance of obs in bs, or -1 if obs is not present in bs.

func (Bytes) IndexByte

func (bs Bytes) IndexByte(b byte) Int

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

func (bs Bytes) IndexRune(r rune) Int

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

func (bs Bytes) IntBE() Int

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

func (bs Bytes) IntLE() Int

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) IsASCII added in v1.0.228

func (bs Bytes) IsASCII() bool

IsASCII checks if all bytes in the Bytes are ASCII bytes.

func (Bytes) IsDigit added in v1.0.228

func (bs Bytes) IsDigit() bool

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) IsEmpty added in v1.0.202

func (bs Bytes) IsEmpty() bool

IsEmpty checks if the Bytes is empty.

func (Bytes) IsLower added in v1.0.195

func (bs Bytes) IsLower() bool

IsLower reports whether bs contains at least one letter and no uppercase letters.

func (Bytes) IsTitle added in v1.0.213

func (bs Bytes) IsTitle() bool

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

func (bs Bytes) IsUpper() bool

IsUpper reports whether bs contains at least one letter and no lowercase letters.

func (Bytes) LastIndex

func (bs Bytes) LastIndex(obs Bytes) Int

LastIndex returns the index of the last instance of obs in bs, or -1 if obs is not present in bs.

func (Bytes) LastIndexByte

func (bs Bytes) LastIndexByte(b byte) Int

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

func (bs Bytes) LeftJustify(length Int, pad Bytes) Bytes

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) Len

func (bs Bytes) Len() Int

Len returns the length of the Bytes.

func (Bytes) LenRunes

func (bs Bytes) LenRunes() Int

LenRunes returns the number of runes in the Bytes.

func (Bytes) Lines added in v1.0.225

func (bs Bytes) Lines() []Bytes

Lines splits the Bytes by lines, with trailing whitespace trimmed per line. See String.Lines for why the return type is a plain slice.

func (Bytes) Lower

func (bs Bytes) Lower() Bytes

Lower converts the Bytes to lowercase.

func (Bytes) Lt

func (bs Bytes) Lt(obs Bytes) bool

Lt checks if the Bytes is less than another Bytes.

func (Bytes) Lte added in v1.0.225

func (bs Bytes) Lte(obs Bytes) bool

Lte checks if the Bytes is less than or equal to another Bytes.

func (Bytes) Map

func (bs Bytes) Map(fn func(rune) rune) Bytes

Map applies a function to each rune in the Bytes and returns the modified Bytes.

func (Bytes) Max added in v1.0.225

func (bs Bytes) Max(b ...Bytes) Bytes

Max returns the maximum of Bytes.

func (Bytes) Min added in v1.0.225

func (bs Bytes) Min(b ...Bytes) Bytes

Min returns the minimum of Bytes.

func (Bytes) Ne

func (bs Bytes) Ne(obs Bytes) bool

Ne checks if the Bytes is not equal to another Bytes.

func (Bytes) NormalizeNFC

func (bs Bytes) NormalizeNFC() Bytes

NormalizeNFC returns a new Bytes with its Unicode characters normalized using the NFC form.

func (Bytes) Prepend added in v1.0.164

func (bs Bytes) Prepend(obs Bytes) Bytes

Prepend prepends the given Bytes to the current Bytes.

func (Bytes) Print

func (bs Bytes) Print() Bytes

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

func (bs Bytes) Println() Bytes

Println writes the content of the Bytes to the standard output (console) with a newline and returns the Bytes unchanged.

func (Bytes) Reader

func (bs Bytes) Reader() *bytes.Reader

Reader returns a *bytes.Reader initialized with the content of Bytes.

func (Bytes) Remove added in v1.0.228

func (bs Bytes) Remove(patterns ...Bytes) Bytes

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

func (bs Bytes) Repeat(count Int) Bytes

Repeat returns a new Bytes consisting of the current Bytes repeated 'count' times.

func (Bytes) Replace

func (bs Bytes) Replace(oldB, newB Bytes, n Int) Bytes

Replace replaces the first 'n' occurrences of 'oldB' with 'newB' in the Bytes.

func (Bytes) ReplaceAll

func (bs Bytes) ReplaceAll(oldB, newB Bytes) Bytes

ReplaceAll replaces all occurrences of 'oldB' with 'newB' in the Bytes.

func (Bytes) ReplaceMulti added in v1.0.228

func (bs Bytes) ReplaceMulti(oldnew ...Bytes) Bytes

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 first matching pattern in argument order 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

func (bs Bytes) ReplaceNth(oldB, newB Bytes, n Int) Bytes

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

func (bs Bytes) Reverse() Bytes

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

func (bs Bytes) RightJustify(length Int, pad Bytes) Bytes

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) Runes added in v1.0.81

func (bs Bytes) Runes() []rune

Runes returns the Bytes as a plain slice of runes.

func (*Bytes) Scan added in v1.0.198

func (bs *Bytes) Scan(src any) error

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

func (bs Bytes) Similarity(obs Bytes) Float

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

func (bs Bytes) Split(sep Bytes) []Bytes

Split splits the Bytes by the specified separator. If sep is empty, the Bytes are split after each UTF-8 rune. See String.Lines for why the return type is a plain slice.

func (Bytes) SplitAfter added in v1.0.77

func (bs Bytes) SplitAfter(sep Bytes) []Bytes

SplitAfter splits the Bytes after each instance of the specified separator. See String.Lines for why the return type is a plain slice.

func (Bytes) SplitN added in v1.0.225

func (bs Bytes) SplitN(sep Bytes, n Int) []Bytes

SplitN splits the Bytes into subslices using the provided separator and returns a plain []Bytes of the results (convert with Slice[Bytes] for chaining). The n parameter controls the number of subslices to return: - If n is negative, there is no limit on the number of subslices returned. - If n is zero, an empty slice is returned. - If n is positive, at most n subslices are returned.

func (Bytes) StartsWith added in v1.0.225

func (bs Bytes) StartsWith(prefix Bytes) bool

StartsWith checks if the Bytes starts with the specified prefix.

func (Bytes) StartsWithAny added in v1.0.225

func (bs Bytes) StartsWithAny(prefixes ...Bytes) bool

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) Std

func (bs Bytes) Std() []byte

Std returns the Bytes as a byte slice.

func (Bytes) String added in v1.0.81

func (bs Bytes) String() String

String returns the Bytes as an String.

func (Bytes) StringUnsafe added in v1.0.147

func (bs Bytes) StringUnsafe() String

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

func (bs Bytes) StripPrefix(cutset Bytes) Bytes

StripPrefix trims the specified Bytes prefix from the Bytes.

func (Bytes) StripSuffix added in v1.0.81

func (bs Bytes) StripSuffix(cutset Bytes) Bytes

StripSuffix trims the specified Bytes suffix from the Bytes.

func (Bytes) SubBytes added in v1.0.228

func (bs Bytes) SubBytes(start, end Int, step ...Int) Bytes

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) Title

func (bs Bytes) Title() Bytes

Title converts the Bytes to title case.

func (Bytes) Transform added in v1.0.89

func (bs Bytes) Transform[U any](fn func(Bytes) U) U

Transform applies a transformation function to the Bytes and returns the result.

func (Bytes) Trim

func (bs Bytes) Trim() Bytes

Trim trims leading and trailing white space from the Bytes.

func (Bytes) TrimEnd added in v1.0.81

func (bs Bytes) TrimEnd() Bytes

TrimEnd removes trailing white space from the Bytes.

func (Bytes) TrimEndSet added in v1.0.82

func (bs Bytes) TrimEndSet(cutset String) Bytes

TrimEndSet removes the specified set of characters from the end of the Bytes.

func (Bytes) TrimSet added in v1.0.82

func (bs Bytes) TrimSet(cutset String) Bytes

TrimSet trims the specified set of characters from both the beginning and end of the Bytes.

func (Bytes) TrimStart added in v1.0.81

func (bs Bytes) TrimStart() Bytes

TrimStart removes leading white space from the Bytes.

func (Bytes) TrimStartSet added in v1.0.82

func (bs Bytes) TrimStartSet(cutset String) Bytes

TrimStartSet removes the specified set of characters from the beginning of the Bytes.

func (Bytes) Truncate added in v1.0.228

func (bs Bytes) Truncate(max Int) Bytes

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

func (bs Bytes) TryBigInt() Result[*big.Int]

TryBigInt parses the Bytes as a *big.Int, mirroring String.TryBigInt.

func (Bytes) TryBool added in v1.0.228

func (bs Bytes) TryBool() Result[bool]

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

func (bs Bytes) TryFloat() Result[Float]

TryFloat parses the Bytes as a float, mirroring String.TryFloat.

func (Bytes) TryInt added in v1.0.228

func (bs Bytes) TryInt() Result[Int]

TryInt parses the Bytes as an integer, mirroring String.TryInt.

func (Bytes) TryUint added in v1.0.228

func (bs Bytes) TryUint() Result[uint]

TryUint parses the Bytes as an unsigned integer, mirroring String.TryUint.

func (Bytes) Upper

func (bs Bytes) Upper() Bytes

Upper converts the Bytes to uppercase.

func (Bytes) Value added in v1.0.198

func (bs Bytes) Value() (driver.Value, error)

Value implements the database/sql/driver.Valuer interface for g.Bytes.

Behavior:

  • Returns the underlying byte slice, ready for database insertion.
  • Always returns a value compatible with SQL BLOB / BYTEA types.

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 DequeOf added in v1.0.181

func DequeOf[T any](elements ...T) *Deque[T]

DequeOf creates a new Deque containing the provided elements.

func NewDeque added in v1.0.181

func NewDeque[T any](capacity ...Int) *Deque[T]

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

func (dq *Deque[T]) Back() Option[T]

Back returns the last element of the Deque. Returns None if the Deque is empty.

func (*Deque[T]) BinarySearch added in v1.0.181

func (dq *Deque[T]) BinarySearch(value T, fn func(T, T) cmp.Ordering) (Int, bool)

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, and a boolean reporting whether the value was found.

func (*Deque[T]) Capacity added in v1.0.181

func (dq *Deque[T]) Capacity() Int

Capacity returns the current capacity of the Deque.

func (*Deque[T]) Clear added in v1.0.181

func (dq *Deque[T]) Clear()

Clear removes all elements from the Deque.

func (*Deque[T]) Clone added in v1.0.181

func (dq *Deque[T]) Clone() *Deque[T]

Clone creates a deep copy of the Deque.

func (*Deque[T]) Contains added in v1.0.181

func (dq *Deque[T]) Contains(value T) bool

Contains checks if the Deque contains the specified value.

func (*Deque[T]) ContainsAll added in v1.0.225

func (dq *Deque[T]) ContainsAll(values ...T) bool

ContainsAll checks if the Deque contains all of the provided values.

func (*Deque[T]) ContainsAny added in v1.0.225

func (dq *Deque[T]) ContainsAny(values ...T) bool

ContainsAny checks if the Deque contains any element from the provided values.

func (*Deque[T]) Eq added in v1.0.181

func (dq *Deque[T]) Eq(other *Deque[T]) bool

Eq checks if two Deques are equal.

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

func (dq *Deque[T]) Front() Option[T]

Front returns the first element of the Deque. Returns None if the Deque is empty.

func (*Deque[T]) Get added in v1.0.181

func (dq *Deque[T]) Get(index Int) Option[T]

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

func (dq *Deque[T]) Index(value T) Int

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

func (dq *Deque[T]) Insert(index Int, value T)

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

func (dq *Deque[T]) IsEmpty() bool

IsEmpty returns true if the Deque contains no elements.

func (*Deque[T]) Iter added in v1.0.181

func (dq *Deque[T]) Iter() Seq[T]

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

func (dq *Deque[T]) IterReverse() Seq[T]

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]) Len added in v1.0.181

func (dq *Deque[T]) Len() Int

Len returns the number of elements in the Deque.

func (*Deque[T]) MakeContiguous added in v1.0.181

func (dq *Deque[T]) MakeContiguous() Slice[T]

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]) Ne added in v1.0.225

func (dq *Deque[T]) Ne(other *Deque[T]) bool

Ne checks if two Deques are not equal.

func (*Deque[T]) PopBack added in v1.0.181

func (dq *Deque[T]) PopBack() Option[T]

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

func (dq *Deque[T]) PopFront() Option[T]

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

func (dq *Deque[T]) Print() *Deque[T]

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

func (dq *Deque[T]) Println() *Deque[T]

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

func (dq *Deque[T]) Remove(index Int) Option[T]

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

func (dq *Deque[T]) Reserve(additional Int)

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

func (dq *Deque[T]) Retain(predicate func(T) bool)

Retain keeps only the elements specified by the predicate.

func (*Deque[T]) RotateLeft added in v1.0.181

func (dq *Deque[T]) RotateLeft(mid Int)

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

func (dq *Deque[T]) RotateRight(k Int)

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

func (dq *Deque[T]) Set(index Int, value T) Option[T]

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]) String added in v1.0.181

func (dq *Deque[T]) String() string

String returns a string representation of the Deque.

func (*Deque[T]) Swap added in v1.0.181

func (dq *Deque[T]) Swap(i, j Int)

Swap swaps the elements at indices i and j. Panics if either index is out of bounds.

func (*Deque[T]) Transform added in v1.0.225

func (dq *Deque[T]) Transform[U any](fn func(*Deque[T]) U) U

Transform applies a transformation function to the Deque and returns the result.

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 Float

type Float float64

Float is a wrapper around 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) Abs

func (f Float) Abs() Float

Abs returns the absolute value of the Float.

func (Float) Acos added in v1.0.228

func (f Float) Acos() Float

Acos returns the arccosine of the Float, in radians.

func (Float) Acosh added in v1.0.228

func (f Float) Acosh() Float

Acosh returns the inverse hyperbolic cosine of the Float.

func (Float) Add

func (f Float) Add(b Float) Float

Add adds two Floats and returns the result.

func (Float) Asin added in v1.0.228

func (f Float) Asin() Float

Asin returns the arcsine of the Float, in radians.

func (Float) Asinh added in v1.0.228

func (f Float) Asinh() Float

Asinh returns the inverse hyperbolic sine of the Float.

func (Float) Atan added in v1.0.228

func (f Float) Atan() Float

Atan returns the arctangent of the Float, in radians.

func (Float) Atan2 added in v1.0.228

func (f Float) Atan2(b Float) Float

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) Atanh added in v1.0.228

func (f Float) Atanh() Float

Atanh returns the inverse hyperbolic tangent of the Float.

func (Float) BigFloat added in v1.0.81

func (f Float) BigFloat() *big.Float

BigFloat returns the Float as a *big.Float.

func (Float) Bits added in v1.0.179

func (f Float) Bits() uint64

Bits returns IEEE-754 representation of f.

func (Float) BytesBE added in v1.0.180

func (f Float) BytesBE() Bytes

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

func (f Float) BytesLE() Bytes

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) Cbrt added in v1.0.228

func (f Float) Cbrt() Float

Cbrt returns the cube root of the Float.

func (Float) Ceil added in v1.0.228

func (f Float) Ceil() Float

Ceil returns the least integer value greater than or equal to the Float.

func (Float) CeilDecimal added in v1.0.194

func (f Float) CeilDecimal(precision Int) Float

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

func (f Float) Clamp(min, max Float) Float

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

func (f Float) Cmp(b Float) cmp.Ordering

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

func (f Float) Copysign(sign Float) Float

Copysign returns a Float with the magnitude of the Float and the sign of sign.

func (Float) Cos added in v1.0.228

func (f Float) Cos() Float

Cos returns the cosine of the Float (in radians).

func (Float) Cosh added in v1.0.228

func (f Float) Cosh() Float

Cosh returns the hyperbolic cosine of the Float.

func (Float) Div

func (f Float) Div(b Float) Float

Div divides two Floats and returns the result.

func (Float) Eq

func (f Float) Eq(b Float) bool

Eq checks if two Floats are equal.

func (Float) Exp added in v1.0.228

func (f Float) Exp() Float

Exp returns e**f, the base-e exponential of the Float.

func (Float) Exp2 added in v1.0.228

func (f Float) Exp2() Float

Exp2 returns 2**f, the base-2 exponential of the Float.

func (Float) ExpM1 added in v1.0.228

func (f Float) ExpM1() Float

ExpM1 returns e**f - 1, which is more accurate than Exp().Sub(1) when the Float is near zero.

func (Float) Float32 added in v1.0.81

func (f Float) Float32() float32

Float32 returns the Float as a float32.

func (Float) Floor added in v1.0.228

func (f Float) Floor() Float

Floor returns the greatest integer value less than or equal to the Float.

func (Float) FloorDecimal added in v1.0.194

func (f Float) FloorDecimal(precision Int) Float

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

func (f Float) Fract() Float

Fract returns the fractional part of the Float (f - f.Trunc()). For NaN and ±Inf the result is NaN.

func (Float) Gt

func (f Float) Gt(b Float) bool

Gt checks if the Float is greater than the specified Float.

func (Float) Gte added in v1.0.208

func (f Float) Gte(b Float) bool

Gte checks if the Float is greater than or equal to the specified Float.

func (Float) Hypot added in v1.0.228

func (f Float) Hypot(b Float) Float

Hypot returns Sqrt(f*f + b*b), avoiding unnecessary overflow and underflow.

func (Float) Int added in v1.0.81

func (f Float) Int() Int

Int returns the Float as an Int.

func (Float) IsFinite added in v1.0.228

func (f Float) IsFinite() bool

IsFinite reports whether the Float is neither NaN nor an infinity.

func (Float) IsInf added in v1.0.228

func (f Float) IsInf() bool

IsInf reports whether the Float is an infinity, either positive or negative.

func (Float) IsNaN added in v1.0.228

func (f Float) IsNaN() bool

IsNaN reports whether the Float is an IEEE 754 "not-a-number" value.

func (Float) IsNormal added in v1.0.228

func (f Float) IsNormal() bool

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

func (f Float) IsSignNegative() bool

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

func (f Float) IsSignPositive() bool

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) IsZero

func (f Float) IsZero() bool

IsZero checks if the Float is 0.

func (Float) Ln added in v1.0.228

func (f Float) Ln() Float

Ln returns the natural logarithm of the Float.

func (Float) Ln1p added in v1.0.228

func (f Float) Ln1p() Float

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) Log2 added in v1.0.228

func (f Float) Log2() Float

Log2 returns the base-2 logarithm of the Float.

func (Float) Log10 added in v1.0.228

func (f Float) Log10() Float

Log10 returns the base-10 logarithm of the Float.

func (Float) Lt

func (f Float) Lt(b Float) bool

Lt checks if the Float is less than the specified Float.

func (Float) Lte added in v1.0.208

func (f Float) Lte(b Float) bool

Lte checks if the Float is less than or equal to the specified Float.

func (Float) Max

func (f Float) Max(b ...Float) Float

Max returns the maximum of Floats.

func (Float) Min

func (f Float) Min(b ...Float) Float

Min returns the minimum of Floats.

func (Float) Mod added in v1.0.194

func (f Float) Mod(b Float) Float

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) Mul

func (f Float) Mul(b Float) Float

Mul multiplies two Floats and returns the result.

func (Float) MulAdd added in v1.0.228

func (f Float) MulAdd(b, c Float) Float

MulAdd returns f*b + c computed as a fused multiply-add with only one rounding.

func (Float) Ne

func (f Float) Ne(b Float) bool

Ne checks if two Floats are not equal.

func (Float) Neg added in v1.0.228

func (f Float) Neg() Float

Neg returns the Float with its sign inverted.

func (Float) Pow added in v1.0.194

func (f Float) Pow(exp Float) Float

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

func (f Float) Print() Float

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

func (f Float) Println() Float

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

func (f Float) Recip() Float

Recip returns the reciprocal (multiplicative inverse) of the Float, 1/f.

func (Float) Round

func (f Float) Round() Int

Round rounds the Float to the nearest integer and returns the result as an Int.

func (Float) RoundDecimal

func (f Float) RoundDecimal(precision Int) Float

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

func (f *Float) Scan(src any) error

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

func (f Float) Signum() Float

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) Sin added in v1.0.228

func (f Float) Sin() Float

Sin returns the sine of the Float (in radians).

func (Float) Sinh added in v1.0.228

func (f Float) Sinh() Float

Sinh returns the hyperbolic sine of the Float.

func (Float) Sqrt added in v1.0.194

func (f Float) Sqrt() Float

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) Std

func (f Float) Std() float64

Std returns the Float as a float64.

func (Float) String added in v1.0.81

func (f Float) String() String

String returns the Float as an String.

func (Float) Sub

func (f Float) Sub(b Float) Float

Sub subtracts two Floats and returns the result.

func (Float) Tan added in v1.0.228

func (f Float) Tan() Float

Tan returns the tangent of the Float (in radians).

func (Float) Tanh added in v1.0.228

func (f Float) Tanh() Float

Tanh returns the hyperbolic tangent of the Float.

func (Float) ToDegrees added in v1.0.228

func (f Float) ToDegrees() Float

ToDegrees converts the Float from radians to degrees.

func (Float) ToRadians added in v1.0.228

func (f Float) ToRadians() Float

ToRadians converts the Float from degrees to radians.

func (Float) Transform added in v1.0.89

func (f Float) Transform[U any](fn func(Float) U) U

Transform applies a transformation function to the Float and returns the result.

func (Float) Trunc added in v1.0.228

func (f Float) Trunc() Float

Trunc returns the integer part of the Float, rounding toward zero.

func (Float) TruncDecimal added in v1.0.194

func (f Float) TruncDecimal(precision Int) Float

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.

func (Float) Value added in v1.0.198

func (f Float) Value() (driver.Value, error)

Value implements the database/sql/driver.Valuer interface for g.Float.

Behavior:

  • Returns the underlying float64 value, ready for database insertion.
  • Always returns a value compatible with SQL REAL / DOUBLE types.

type Formattable added in v1.0.228

type Formattable interface {
	FormatValue(spec String) String
}

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 HeapOf added in v1.0.228

func HeapOf[T any](compareFn func(T, T) cmp.Ordering, values ...T) *Heap[T]

HeapOf creates a new Heap with the given comparison function containing the provided elements.

func NewHeap added in v1.0.181

func NewHeap[T any](compareFn func(T, T) cmp.Ordering) *Heap[T]

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, 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]) Clone added in v1.0.181

func (h *Heap[T]) Clone() *Heap[T]

Clone creates a deep copy of the heap.

func (*Heap[T]) Contains added in v1.0.225

func (h *Heap[T]) Contains(value T) bool

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

func (h *Heap[T]) Eq(other *Heap[T]) bool

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

func (h *Heap[T]) Fix(i Int)

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

func (h *Heap[T]) IntoIter() Seq[T]

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:

- Seq[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
result := heap.IntoIter().Collect().Heap(cmp.Cmp) // [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]) IsEmpty added in v1.0.202

func (h *Heap[T]) IsEmpty() bool

IsEmpty returns true if the heap contains no elements.

func (*Heap[T]) Iter added in v1.0.181

func (h *Heap[T]) Iter() Seq[T]

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:

- Seq[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
// (the Heap materializer requires a comparison function)
firstThree := heap.Iter().Take(3).Collect().Heap(cmp.Cmp) // [1, 5, 8]
evenNumbers := heap.Iter().Filter(func(x int) bool {
	return x%2 == 0
}).Collect().Heap(cmp.Cmp) // [8, 10]

func (*Heap[T]) Len added in v1.0.181

func (h *Heap[T]) Len() Int

Len returns the number of elements in the heap.

func (*Heap[T]) Ne added in v1.0.228

func (h *Heap[T]) Ne(other *Heap[T]) bool

Ne checks if two Heaps are not equal.

func (*Heap[T]) Peek added in v1.0.181

func (h *Heap[T]) Peek() Option[T]

Peek returns the top element without removing it. Returns None if the heap is empty.

func (*Heap[T]) Pop added in v1.0.181

func (h *Heap[T]) Pop() Option[T]

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

func (h *Heap[T]) Print() *Heap[T]

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

func (h *Heap[T]) Println() *Heap[T]

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

func (h *Heap[T]) Remove(i Int) Option[T]

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 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

func (h *Heap[T]) Slice() Slice[T]

Slice returns a slice containing all elements in the heap. The order is not guaranteed to be sorted.

func (*Heap[T]) String added in v1.0.181

func (h *Heap[T]) String() string

String returns a string representation of the heap.

func (*Heap[T]) Transform added in v1.0.181

func (h *Heap[T]) Transform[U any](fn func(*Heap[T]) U) U

Transform applies a transformation function to the Heap and returns the result.

type Int

type Int int

Int is a wrapper around 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

func (i Int) Abs() Int

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

func (i Int) Add(b Int) Int

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) BigInt added in v1.0.81

func (i Int) BigInt() *big.Int

BigInt returns the Int as a *big.Int.

func (Int) Binary added in v1.0.81

func (i Int) Binary() String

Binary returns the Int as a binary string, zero-padded to a minimum width of 8 characters (the sign counts toward the width for negative values).

func (Int) BytesBE added in v1.0.180

func (i Int) BytesBE() Bytes

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

func (i Int) BytesLE() Bytes

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

func (i Int) CheckedAbs() Option[Int]

CheckedAbs returns the absolute value of the Int, returning None if it overflows (i == MinInt).

func (Int) CheckedAdd added in v1.0.228

func (i Int) CheckedAdd(b Int) Option[Int]

CheckedAdd adds two Ints, returning None if the addition overflows.

func (Int) CheckedDiv added in v1.0.228

func (i Int) CheckedDiv(b Int) Option[Int]

CheckedDiv divides the Int by b, returning None if b is zero or the division overflows.

func (Int) CheckedMul added in v1.0.228

func (i Int) CheckedMul(b Int) Option[Int]

CheckedMul multiplies two Ints, returning None if the multiplication overflows.

func (Int) CheckedNeg added in v1.0.228

func (i Int) CheckedNeg() Option[Int]

CheckedNeg negates the Int, returning None if the negation overflows (i == MinInt).

func (Int) CheckedPow added in v1.0.228

func (i Int) CheckedPow(exp Int) Option[Int]

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

func (i Int) CheckedRem(b Int) Option[Int]

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

func (i Int) CheckedSub(b Int) Option[Int]

CheckedSub subtracts b from the Int, returning None if the subtraction overflows.

func (Int) Clamp added in v1.0.228

func (i Int) Clamp(min, max Int) Int

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) Cmp added in v1.0.70

func (i Int) Cmp(b Int) cmp.Ordering

Cmp compares two Ints and returns an cmp.Ordering.

func (Int) Div

func (i Int) Div(b Int) Int

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) Eq

func (i Int) Eq(b Int) bool

Eq checks if two Ints are equal.

func (Int) Float added in v1.0.81

func (i Int) Float() Float

Float returns the Int as an Float.

func (Int) Gt

func (i Int) Gt(b Int) bool

Gt checks if the Int is greater than the specified Int.

func (Int) Gte

func (i Int) Gte(b Int) bool

Gte checks if the Int is greater than or equal to the specified Int.

func (Int) Hex added in v1.0.81

func (i Int) Hex() String

Hex returns the Int as a hexadecimal string.

func (Int) Int8 added in v1.0.81

func (i Int) Int8() int8

Int8 returns the Int as an int8.

func (Int) Int16 added in v1.0.81

func (i Int) Int16() int16

Int16 returns the Int as an int16.

func (Int) Int32 added in v1.0.81

func (i Int) Int32() int32

Int32 returns the Int as an int32.

func (Int) Int64 added in v1.0.81

func (i Int) Int64() int64

Int64 returns the Int as an int64.

func (Int) IsNegative

func (i Int) IsNegative() bool

IsNegative checks if the Int is negative.

func (Int) IsPositive

func (i Int) IsPositive() bool

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) IsZero

func (i Int) IsZero() bool

IsZero checks if the Int is 0.

func (Int) Lt

func (i Int) Lt(b Int) bool

Lt checks if the Int is less than the specified Int.

func (Int) Lte

func (i Int) Lte(b Int) bool

Lte checks if the Int is less than or equal to the specified Int.

func (Int) Max

func (i Int) Max(b ...Int) Int

Max returns the maximum of Ints.

func (Int) Min

func (i Int) Min(b ...Int) Int

Min returns the minimum of Ints.

func (Int) Mul

func (i Int) Mul(b Int) Int

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) Ne

func (i Int) Ne(b Int) bool

Ne checks if two Ints are not equal.

func (Int) Neg added in v1.0.228

func (i Int) Neg() Int

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) Octal added in v1.0.81

func (i Int) Octal() String

Octal returns the Int as an octal string.

func (Int) OverflowingAdd added in v1.0.228

func (i Int) OverflowingAdd(b Int) (Int, bool)

OverflowingAdd adds two Ints, returning the wrapped result and a flag indicating overflow.

func (Int) OverflowingMul added in v1.0.228

func (i Int) OverflowingMul(b Int) (Int, bool)

OverflowingMul multiplies two Ints, returning the wrapped result and a flag indicating overflow.

func (Int) OverflowingSub added in v1.0.228

func (i Int) OverflowingSub(b Int) (Int, bool)

OverflowingSub subtracts b from the Int, returning the wrapped result and a flag indicating overflow.

func (Int) Print

func (i Int) Print() Int

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

func (i Int) Println() Int

Println writes the value of the Int to the standard output (console) with a newline and returns the Int unchanged.

func (Int) Rem

func (i Int) Rem(b Int) Int

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

func (i Int) SaturatingAdd(b Int) Int

SaturatingAdd adds two Ints, clamping the result to MinInt or MaxInt on overflow.

func (Int) SaturatingMul added in v1.0.228

func (i Int) SaturatingMul(b Int) Int

SaturatingMul multiplies two Ints, clamping the result to MinInt or MaxInt on overflow.

func (Int) SaturatingSub added in v1.0.228

func (i Int) SaturatingSub(b Int) Int

SaturatingSub subtracts b from the Int, clamping the result to MinInt or MaxInt on overflow.

func (*Int) Scan added in v1.0.198

func (i *Int) Scan(src any) error

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

func (i Int) Signum() Int

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) Std

func (i Int) Std() int

Std returns the Int as an int.

func (Int) String added in v1.0.81

func (i Int) String() String

String returns the Int as an String.

func (Int) Sub

func (i Int) Sub(b Int) Int

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

func (i Int) Transform[U any](fn func(Int) U) U

Transform applies a transformation function to the Int and returns the result.

func (Int) Uint added in v1.1.0

func (i Int) Uint() uint

Uint returns the Int as a uint.

func (Int) Uint8 added in v1.1.0

func (i Int) Uint8() uint8

Uint8 returns the Int as a uint8.

func (Int) Uint16 added in v1.1.0

func (i Int) Uint16() uint16

Uint16 returns the Int as a uint16.

func (Int) Uint32 added in v1.1.0

func (i Int) Uint32() uint32

Uint32 returns the Int as a uint32.

func (Int) Uint64 added in v1.1.0

func (i Int) Uint64() uint64

Uint64 returns the Int as a uint64.

func (Int) Value added in v1.0.198

func (i Int) Value() (driver.Value, error)

Value implements the database/sql/driver.Valuer interface for g.Int.

Behavior:

  • Returns the underlying int64 value, ready for database insertion.
  • Always returns a value compatible with SQL INTEGER type.

type Map

type Map[K comparable, V any] map[K]V

Map is a generic alias for a map.

func MapFromMapOrd added in v1.1.0

func MapFromMapOrd[K comparable, V any](mo MapOrd[K, V]) Map[K, V]

MapFromMapOrd converts an ordered Map to a standard Map.

func MapFromMapSafe added in v1.1.0

func MapFromMapSafe[K comparable, V any](ms *MapSafe[K, V]) Map[K, V]

MapFromMapSafe 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 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]) Clear

func (m Map[K, V]) Clear()

Clear removes all key-value pairs from the Map.

func (Map[K, V]) Clone

func (m Map[K, V]) Clone() Map[K, V]

Clone creates a new Map that is a copy of the original Map.

func (Map[K, V]) Contains

func (m Map[K, V]) Contains(key K) bool

Contains checks if the Map contains the specified key.

func (Map[K, V]) Copy

func (m Map[K, V]) Copy(src Map[K, V])

Copy copies the source Map's key-value pairs to the target Map.

func (Map[K, V]) Entry added in v1.0.153

func (m Map[K, V]) Entry(key K) Entry[K, V]

Entry returns an Entry for the given key.

func (Map[K, V]) Eq

func (m Map[K, V]) Eq(other Map[K, V]) bool

Eq checks if two Maps are equal.

func (Map[K, V]) Get

func (m Map[K, V]) Get(k K) Option[V]

Get retrieves the value associated with the given key.

func (Map[K, V]) Insert added in v1.0.202

func (m Map[K, V]) Insert(key K, value V) Option[V]

Insert sets the value for the key and returns the previous value if it existed.

func (Map[K, V]) IsEmpty added in v1.0.202

func (m Map[K, V]) IsEmpty() bool

IsEmpty checks if the Map is empty.

func (Map[K, V]) Iter

func (m Map[K, V]) Iter() Seq2[K, V]

Iter returns an iterator (Seq2[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:

- Seq2[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]) Keys

func (m Map[K, V]) Keys() Slice[K]

Keys returns a slice of the Map's keys.

func (Map[K, V]) Len

func (m Map[K, V]) Len() Int

Len returns the number of key-value pairs in the Map.

func (Map[K, V]) Ne

func (m Map[K, V]) Ne(other Map[K, V]) bool

Ne checks if two Maps are not equal.

func (Map[K, V]) Print

func (m Map[K, V]) Print() Map[K, V]

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

func (m Map[K, V]) Println() Map[K, V]

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

func (m Map[K, V]) Remove(key K) Option[V]

Remove removes the specified key from the Map and returns the removed value.

func (Map[K, V]) Std

func (m Map[K, V]) Std() map[K]V

Std converts the Map to a regular Go map.

func (Map[K, V]) String

func (m Map[K, V]) String() string

String returns a string representation of the Map.

func (Map[K, V]) Transform added in v1.0.89

func (m Map[K, V]) Transform[U any](fn func(Map[K, V]) U) U

Transform applies a transformation function to the Map and returns the result.

func (Map[K, V]) Values

func (m Map[K, V]) Values() Slice[V]

Values returns a slice of the Map's values.

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 MapOrdFromMap

func MapOrdFromMap[K comparable, V any](m Map[K, V]) MapOrd[K, V]

MapOrdFromMap converts a standard Map to an ordered Map.

func MapOrdFromMapSafe added in v1.1.0

func MapOrdFromMapSafe[K comparable, V any](ms *MapSafe[K, V]) MapOrd[K, V]

MapOrdFromMapSafe 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 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]) Clone

func (mo MapOrd[K, V]) Clone() MapOrd[K, V]

Clone creates a new ordered Map with the same key-value pairs.

func (MapOrd[K, V]) Contains

func (mo MapOrd[K, V]) Contains(key K) bool

Contains checks if the ordered Map contains the specified key.

func (*MapOrd[K, V]) Copy

func (mo *MapOrd[K, V]) Copy(src MapOrd[K, V])

Copy copies key-value pairs from the source ordered Map to the current ordered Map.

func (*MapOrd[K, V]) Entry added in v1.0.153

func (mo *MapOrd[K, V]) Entry(key K) OrdEntry[K, V]

Entry returns an OrdEntry for the given key.

func (MapOrd[K, V]) Eq

func (mo MapOrd[K, V]) Eq(other MapOrd[K, V]) bool

Eq compares the current ordered Map to another ordered Map and returns true if they are equal.

func (MapOrd[K, V]) Get

func (mo MapOrd[K, V]) Get(key K) Option[V]

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

func (mo *MapOrd[K, V]) Insert(key K, value V) Option[V]

Insert sets the value for the specified key in the ordered Map, and returns the previous value if it existed.

func (MapOrd[K, V]) IsEmpty added in v1.0.202

func (mo MapOrd[K, V]) IsEmpty() bool

IsEmpty checks if the ordered Map is empty.

func (MapOrd[K, V]) IsSortedBy added in v1.0.192

func (mo MapOrd[K, V]) IsSortedBy(fn func(a, b Pair[K, V]) cmp.Ordering) bool

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

func (mo MapOrd[K, V]) IsSortedByKey(fn func(a, b K) cmp.Ordering) bool

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

func (mo MapOrd[K, V]) IsSortedByValue(fn func(a, b V) cmp.Ordering) bool

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

func (mo MapOrd[K, V]) Iter() Seq2[K, V]

Iter returns an iterator (Seq2[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 Seq2[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

func (mo MapOrd[K, V]) IterReverse() Seq2[K, V]

IterReverse returns an iterator (Seq2[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 Seq2[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]) Keys

func (mo MapOrd[K, V]) Keys() Slice[K]

Keys returns an Slice containing all the keys in the ordered Map.

func (MapOrd[K, V]) Len

func (mo MapOrd[K, V]) Len() Int

Len returns the number of key-value pairs in the ordered Map.

func (MapOrd[K, V]) Ne

func (mo MapOrd[K, V]) Ne(other MapOrd[K, V]) bool

Ne compares the current ordered Map to another ordered Map and returns true if they are not equal.

func (MapOrd[K, V]) Print

func (mo MapOrd[K, V]) Print() MapOrd[K, V]

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

func (mo MapOrd[K, V]) Println() MapOrd[K, V]

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

func (mo *MapOrd[K, V]) Remove(key K) Option[V]

Remove removes the specified key from the ordered Map and returns the removed value.

func (MapOrd[K, V]) SortBy

func (mo MapOrd[K, V]) SortBy(fn func(a, b Pair[K, V]) cmp.Ordering)

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

func (mo MapOrd[K, V]) SortByKey(fn func(a, b K) cmp.Ordering)

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

func (mo MapOrd[K, V]) SortByValue(fn func(a, b V) cmp.Ordering)

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) })

func (MapOrd[K, V]) String

func (mo MapOrd[K, V]) String() string

String returns a string representation of the ordered Map.

func (MapOrd[K, V]) Transform added in v1.0.89

func (mo MapOrd[K, V]) Transform[U any](fn func(MapOrd[K, V]) U) U

Transform applies a transformation function to the MapOrd and returns the result.

func (MapOrd[K, V]) Values

func (mo MapOrd[K, V]) Values() Slice[V]

Values returns an Slice containing all the values in the ordered Map.

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 MapSafeFromMap added in v1.1.0

func MapSafeFromMap[K comparable, V any](m Map[K, V]) *MapSafe[K, V]

MapSafeFromMap converts a standard Map to a thread-safe Map.

func MapSafeFromMapOrd added in v1.1.0

func MapSafeFromMapOrd[K comparable, V any](mo MapOrd[K, V]) *MapSafe[K, V]

MapSafeFromMapOrd converts an ordered Map to a thread-safe Map.

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]) Clone added in v1.0.111

func (ms *MapSafe[K, V]) Clone() *MapSafe[K, V]

Clone creates a deep copy of the MapSafe.

func (*MapSafe[K, V]) Contains added in v1.0.111

func (ms *MapSafe[K, V]) Contains(key K) bool

Contains checks if the MapSafe contains the specified key.

func (*MapSafe[K, V]) Copy added in v1.0.111

func (ms *MapSafe[K, V]) Copy(src *MapSafe[K, V])

Copy performs a deep copy of the source MapSafe's pairs into the current map.

func (*MapSafe[K, V]) Entry added in v1.0.166

func (ms *MapSafe[K, V]) Entry(key K) SafeEntry[K, V]

Entry returns a SafeEntry for the given key.

func (*MapSafe[K, V]) Eq added in v1.0.111

func (ms *MapSafe[K, V]) Eq(other *MapSafe[K, V]) bool

Eq checks if two MapSafes are equal by deep-comparing their values.

func (*MapSafe[K, V]) Get added in v1.0.111

func (ms *MapSafe[K, V]) Get(key K) Option[V]

Get retrieves the value associated with the given key.

func (*MapSafe[K, V]) Insert added in v1.0.202

func (ms *MapSafe[K, V]) Insert(key K, value V) Option[V]

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]) IsEmpty added in v1.0.202

func (ms *MapSafe[K, V]) IsEmpty() bool

IsEmpty checks if the MapSafe is empty.

func (*MapSafe[K, V]) Iter added in v1.0.111

func (ms *MapSafe[K, V]) Iter() Seq2[K, V]

Iter provides a thread-safe iterator over the MapSafe's key-value pairs.

func (*MapSafe[K, V]) Keys added in v1.0.111

func (ms *MapSafe[K, V]) Keys() Slice[K]

Keys returns a slice of the MapSafe's keys.

func (*MapSafe[K, V]) Len added in v1.0.111

func (ms *MapSafe[K, V]) Len() Int

Len returns the number of key-value pairs in the MapSafe.

func (*MapSafe[K, V]) Ne added in v1.0.111

func (ms *MapSafe[K, V]) Ne(other *MapSafe[K, V]) bool

Ne checks if two MapSafes are not equal.

func (*MapSafe[K, V]) Print added in v1.0.111

func (ms *MapSafe[K, V]) Print() *MapSafe[K, V]

Print writes the MapSafe to standard output.

func (*MapSafe[K, V]) Println added in v1.0.122

func (ms *MapSafe[K, V]) Println() *MapSafe[K, V]

Println writes the MapSafe to standard output with a newline.

func (*MapSafe[K, V]) Remove added in v1.0.202

func (ms *MapSafe[K, V]) Remove(key K) Option[V]

Remove removes the specified key from the MapSafe and returns the removed value.

func (*MapSafe[K, V]) String added in v1.0.111

func (ms *MapSafe[K, V]) String() string

String returns a string representation of the MapSafe.

func (*MapSafe[K, V]) Transform added in v1.0.225

func (ms *MapSafe[K, V]) Transform[U any](fn func(*MapSafe[K, V]) U) U

Transform applies a transformation function to the MapSafe and returns the result.

func (*MapSafe[K, V]) TryInsert added in v1.0.202

func (ms *MapSafe[K, V]) TryInsert(key K, value V) Option[V]

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

func (*MapSafe[K, V]) Values added in v1.0.111

func (ms *MapSafe[K, V]) Values() Slice[V]

Values returns a slice of the MapSafe's values.

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 NewMutex added in v1.0.201

func NewMutex[T any](value T) *Mutex[T]

NewMutex creates a new Mutex containing the given 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.

func (*Mutex[T]) With added in v1.0.208

func (m *Mutex[T]) With(fn func(*T))

With acquires the mutex, calls fn with a pointer to the protected value, and releases the mutex when fn returns. This is a convenience method that eliminates the need for manual Lock/Unlock management.

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

type Named Map[String, any]

Named is a map-like type that stores key-value pairs for resolving named placeholders in Format.

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, 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. If the key was concurrently removed, the zero value of V is inserted and returned.

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. If the key was concurrently removed, the value is inserted as for a vacant entry.

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. If the key was concurrently removed, fn is invoked with the key and its result inserted as for a vacant entry.

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 None

func None[T any]() Option[T]

None creates an Option representing no value.

func OptionFromPtr added in v1.0.221

func OptionFromPtr[T any](ptr *T) Option[T]

OptionFromPtr converts a pointer into an Option. Returns None if ptr is nil.

func OptionOf added in v1.0.97

func OptionOf[T any](value T, ok bool) Option[T]

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 Some

func Some[T any](value T) Option[T]

Some creates an Option containing a value.

func (Option[T]) And added in v1.0.228

func (o Option[T]) And[U any](other Option[U]) Option[U]

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

func (o Option[T]) Expect(msg string) T

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

func (o Option[T]) Filter(pred func(T) bool) Option[T]

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

func (o Option[T]) Inspect(fn func(T)) Option[T]

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]) IsNone

func (o Option[T]) IsNone() bool

IsNone returns true if the Option represents no value.

func (Option[T]) IsNoneOr added in v1.0.228

func (o Option[T]) IsNoneOr(pred func(T) bool) bool

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]) IsSome

func (o Option[T]) IsSome() bool

IsSome returns true if the Option contains a value.

func (Option[T]) IsSomeAnd added in v1.0.220

func (o Option[T]) IsSomeAnd(pred func(T) bool) bool

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

func (o Option[T]) Map[U any](fn func(T) U) Option[U]

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

func (o Option[T]) MapOr[U any](def U, fn func(T) U) U

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

func (o Option[T]) MapOrElse[U any](defFn func() U, fn func(T) U) U

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

func (o Option[T]) MarshalJSON() ([]byte, error)

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

func (o Option[T]) MarshalJSONTo(enc *jsontext.Encoder) error

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]) Option added in v1.0.184

func (o Option[T]) Option() (T, bool)

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

func (o Option[T]) Or(other Option[T]) Option[T]

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

func (o Option[T]) OrElse(fn func() Option[T]) Option[T]

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

func (o *Option[T]) Replace(value T) Option[T]

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

func (o *Option[T]) Scan(src any) error

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

func (o Option[T]) String() string

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

func (o *Option[T]) Take() Option[T]

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

func (o Option[T]) Then[U any](fn func(T) Option[U]) Option[U]

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

func (o Option[T]) ThenOf[U any](fn func(T) (U, bool)) Option[U]

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

func (o *Option[T]) UnmarshalJSON(data []byte) error

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

func (o *Option[T]) UnmarshalJSONFrom(dec *jsontext.Decoder) error

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

func (o Option[T]) Value() (driver.Value, error)

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.

func (Option[T]) Xor added in v1.0.228

func (o Option[T]) Xor(other Option[T]) Option[T]

Xor returns Some if exactly one of the two Options is Some, otherwise None.

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 Pair

type Pair[K, V any] struct {
	Key   K
	Value V
}

Pair is a key-value pair yielded by the key-value sequences.

It is a defined struct rather than an alias so that g's iterator core owns it outright and carries no non-stdlib dependency.

func PairOf added in v1.0.228

func PairOf[K, V any](key K, value V) Pair[K, V]

PairOf creates a Pair from the provided key and value.

Example:

p := g.PairOf("answer", 42) // Pair[string, int]

func (Pair[K, V]) Unpack added in v1.1.0

func (p Pair[K, V]) Unpack() (K, V)

Unpack returns the pair's key and value, enabling tuple-style destructuring.

k, v := p.Unpack()

The two-value result can also feed a (K, V) call site directly:

yield(p.Unpack())

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 Eprint added in v1.0.146

func Eprint[T ~string](format T, args ...any) Result[int]

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

func Eprintln[T ~string](format T, args ...any) Result[int]

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 Err

func Err[T any](err error) Result[T]

Err returns a new Result[T] containing the given error.

func Ok

func Ok[T any](value T) Result[T]

Ok returns a new Result[T] containing the given value.

func OkOr added in v1.1.0

func OkOr[T any](o Option[T], err error) Result[T]

OkOr converts an Option into a Result: Ok(value) if Some, otherwise Err(err).

It is a free function rather than an Option method: as a method every Option[T] instantiation would also instantiate Result[T] (and everything Result's methods mention), even in packages that never convert between the two.

func OkOrElse added in v1.1.0

func OkOrElse[T any](o Option[T], fn func() error) Result[T]

OkOrElse converts an Option into a Result: Ok(value) if Some, otherwise Err(fn()). See OkOr for why this is not a method.

func Print added in v1.0.122

func Print[T ~string](format T, args ...any) Result[int]

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

func Println[T ~string](format T, args ...any) Result[int]

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

func ResultOf[T any](value T, err error) Result[T]

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

func TryFormat[T ~string](template T, args ...any) (result Result[String])

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

func TryFormatTo[T ~string](builder *Builder, template T, args ...any) Result[Unit]

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

func Write[T ~string](w io.Writer, format T, args ...any) Result[int]

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

func Writeln[T ~string](w io.Writer, format T, args ...any) Result[int]

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

func (r Result[T]) And[U any](other Result[U]) Result[U]

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

func (r Result[T]) Err() error

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

func (r Result[T]) ErrAs(target any) bool

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

func (r Result[T]) ErrIs(target error) bool

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

func (r Result[T]) ErrOption() Option[error]

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

func (r Result[T]) ErrSource() Option[error]

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

func (r Result[T]) Expect(msg string) T

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

func (r Result[T]) Inspect(fn func(T)) Result[T]

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

func (r Result[T]) InspectErr(fn func(error)) Result[T]

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]) IsErr

func (r Result[T]) IsErr() bool

IsErr returns true if the Result contains an error.

func (Result[T]) IsErrAnd added in v1.0.228

func (r Result[T]) IsErrAnd(pred func(error) bool) bool

IsErrAnd returns true if the Result is Err and the predicate returns true for the contained error.

func (Result[T]) IsOk

func (r Result[T]) IsOk() bool

IsOk returns true if the Result contains a value (no error).

func (Result[T]) IsOkAnd added in v1.0.228

func (r Result[T]) IsOkAnd(pred func(T) bool) bool

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

func (r Result[T]) Map[U any](fn func(T) U) Result[U]

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

func (r Result[T]) MapErr(fn func(error) error) Result[T]

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

func (r Result[T]) MapOr[U any](def U, fn func(T) U) U

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

func (r Result[T]) MapOrElse[U any](defFn func(error) U, fn func(T) U) U

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

func (r Result[T]) MarshalJSON() ([]byte, error)

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

func (r Result[T]) MarshalJSONTo(enc *jsontext.Encoder) error

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

func (r Result[T]) Option() Option[T]

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

func (r Result[T]) Or(other Result[T]) Result[T]

Or returns the Result if it is Ok, otherwise returns the provided alternative Result.

func (Result[T]) OrElse added in v1.0.228

func (r Result[T]) OrElse(fn func(error) Result[T]) Result[T]

OrElse returns the Result if it is Ok, otherwise calls fn with the error and returns its result.

func (Result[T]) Result

func (r Result[T]) Result() (T, error)

Result returns the value and error, conforming to the standard Go multi-value return pattern.

func (Result[T]) String added in v1.0.60

func (r Result[T]) String() string

String returns a string representation of the Result.

func (Result[T]) Then

func (r Result[T]) Then[U any](fn func(T) Result[U]) Result[U]

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

func (r Result[T]) ThenOf[U any](fn func(T) (U, error)) Result[U]

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

func (r *Result[T]) UnmarshalJSON(data []byte) error

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

func (r *Result[T]) UnmarshalJSONFrom(dec *jsontext.Decoder) error

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

func (r Result[T]) UnwrapErr() error

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.

func (Result[T]) Wrap added in v1.0.207

func (r Result[T]) Wrap(err error) Result[T]

Wrap wraps the error in Result with additional context error. Both errors are preserved in the chain and accessible via ErrIs. If Result is Ok, returns unchanged.

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 NewRwLock added in v1.0.201

func NewRwLock[T any](value T) *RwLock[T]

NewRwLock creates a new RwLock containing the given 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 Seq added in v1.1.0

type Seq[V any] func(yield func(V) bool)

Seq is an iterator over sequences of individual values.

func FromChan added in v1.0.69

func FromChan[V any](ch <-chan V) Seq[V]

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: - Seq[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().Slice().                            // 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) Seq[T]

Range returns a Seq[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) Seq[T]

RangeInclusive returns a Seq[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 (Seq[V]) All added in v1.1.0

func (seq Seq[V]) All(fn func(v V) bool) bool

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 (Seq[V]) Any added in v1.1.0

func (seq Seq[V]) Any(fn func(V) bool) bool

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 (Seq[V]) Chain added in v1.1.0

func (seq Seq[V]) Chain(seqs ...Seq[V]) Seq[V]

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 ([]Seq[V]): Other iterators to be concatenated with the current iterator.

Returns:

- Seq[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().Slice().Print()

Output: [1, 2, 3, 4, 5, 6]

The resulting iterator will contain elements from both iterators in the specified order.

func (Seq[V]) Chan added in v1.1.0

func (seq Seq[V]) Chan(ctxs ...context.Context) chan V

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 (Seq[V]) ChunkBy added in v1.1.0

func (seq Seq[V]) ChunkBy(fn func(a, b V) bool) SeqSlices[V]

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 `Seq` 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().Slices()
// 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 (Seq[V]) Chunks added in v1.1.0

func (seq Seq[V]) Chunks(n Int) SeqSlices[V]

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().Slices()

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 (Seq[V]) Collect added in v1.1.0

func (seq Seq[V]) Collect() collector[V]

Collect returns a collector over the sequence. Collect itself is lazy and does not consume the sequence; only the collector's materializer methods do, turning the elements into a concrete container:

s.Iter().Filter(fn).Collect().Slice()
s.Iter().Filter(fn).Collect().Set[int]()
s.Iter().Collect().Heap(cmp.Cmp)
s.Iter().Collect().Deque()

Set (like Map/MapOrd/MapSafe on the key-value collector) takes the element type as an explicit type argument: Go checks constraints at method DECLARATION, where the sequence's own type parameter is still `any`, so a method of Seq[V any] can never mention Set[V] — the comparable constraint must live on the method's own type parameter, and that parameter cannot be inferred from zero arguments. The other collectors need no annotations.

func (Seq[V]) Combinations added in v1.1.0

func (seq Seq[V]) Combinations(size Int) SeqSlices[V]

Combinations generates all combinations of length 'size' from the sequence.

func (Seq[V]) Context added in v1.1.0

func (seq Seq[V]) Context(ctx context.Context) Seq[V]

Context allows the iteration to be controlled with a context.Context.

func (Seq[V]) Count added in v1.1.0

func (seq Seq[V]) Count() Int

Count consumes the iterator, counting the number of iterations and returning it.

func (Seq[V]) CounterBy added in v1.1.0

func (seq Seq[V]) CounterBy[K comparable](fn func(V) K) Seq2[K, Int]

CounterBy tallies elements by fn(element), returning a Seq2[K, Int] that yields each key with the number of elements that produced it: 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 source is consumed when the returned sequence is iterated. 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() })
// yields 5:2, 4:1 — counts by word length, in first-seen order

func (Seq[V]) Cycle added in v1.1.0

func (seq Seq[V]) Cycle() Seq[V]

Cycle returns an iterator that endlessly repeats the elements of the current sequence.

func (Seq[V]) Dedup added in v1.1.0

func (seq Seq[V]) Dedup() Seq[V]

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: - Seq[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().Slice()
result.Print()

Output: [1 2 3 4 5]

The resulting iterator will contain only unique elements, removing consecutive duplicates.

func (Seq[V]) Enumerate added in v1.1.0

func (seq Seq[V]) Enumerate() Seq2[Int, V]

Enumerate adds an index to each element in the iterator.

Returns:

- Seq2[Int, V]: An iterator yielding (index, value) pairs, 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().MapOrd[g.Int, g.String]()

ps.Print()

Output: MapOrd{0:bbb, 1:ddd, 2:xxx, 3:aaa, 4:ccc}

func (Seq[V]) Exclude added in v1.1.0

func (seq Seq[V]) Exclude(fn func(V) bool) Seq[V]

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:

- Seq[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().Slice()
notEven.Print()

Output: [1, 3, 5]

The resulting iterator will contain only the elements that do not satisfy the provided function.

func (Seq[V]) Filter added in v1.1.0

func (seq Seq[V]) Filter(fn func(V) bool) Seq[V]

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:

- Seq[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().Slice()
even.Print()

Output: [2 4].

The resulting iterator will contain only the elements that satisfy the provided function.

func (Seq[V]) FilterMap added in v1.1.0

func (seq Seq[V]) FilterMap[U any](fn func(V) Option[U]) Seq[U]

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[U]): The function that transforms and filters elements. Returns Some(value) to include the transformed value, or None to filter it out. The result type may differ from the element type.

Returns:

- Seq[U]: 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 (Seq[V]) Find added in v1.1.0

func (seq Seq[V]) Find(fn func(v V) bool) Option[V]

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 := 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 (Seq[V]) FindMap added in v1.1.0

func (seq Seq[V]) FindMap[U any](fn func(V) Option[U]) Option[U]

FindMap applies fn to each element and returns the first Some result, or None if fn returns None for every element.

func (Seq[V]) First added in v1.1.0

func (seq Seq[V]) First() Option[V]

First returns the first element from the sequence.

func (Seq[V]) FlatMap added in v1.1.0

func (seq Seq[V]) FlatMap[U any](fn func(V) Seq[U]) Seq[U]

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) Seq[U]): The function that transforms each element into a sequence. The element type of the resulting sequences may differ.

Returns:

- Seq[U]: 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) Seq[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) Seq[int] {
	return g.Slice[int]{n, n*10, n*100}.Iter()
})
// expanded will yield: 1, 10, 100, 2, 20, 200, 3, 30, 300

func (Seq[V]) Flatten added in v1.1.0

func (seq Seq[V]) Flatten() Seq[V]

Flatten recursively flattens nested slices and arrays inside each element, yielding the leaf elements in order.

The function relies on reflection: slices and arrays at any depth are descended into, and only leaf values assignable to V are yielded.

Returns:

- Seq[V]: A single iterator containing the flattened leaf elements.

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().Slice().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 (Seq[V]) Fold added in v1.1.0

func (seq Seq[V]) Fold[A any](init A, fn func(acc A, val V) A) A

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:

- A: 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 (Seq[V]) ForEach added in v1.1.0

func (seq Seq[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()
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 (Seq[V]) Inspect added in v1.1.0

func (seq Seq[V]) Inspect(fn func(v V)) Seq[V]

Inspect creates a new iterator that wraps around the current iterator and allows inspecting each element as it passes through.

func (Seq[V]) Intersperse added in v1.1.0

func (seq Seq[V]) Intersperse(sep V) Seq[V]

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:

- Seq[V]: An iterator containing elements with the separator interspersed.

Example usage:

g.Slice[string]{"Hello", "World", "!"}.
	Iter().
	Intersperse(" ").
	Collect().
	Slice().
	Join().
	Print()

Output: "Hello World !".

The resulting iterator will contain elements with the separator interspersed.

func (Seq[V]) Last added in v1.1.0

func (seq Seq[V]) Last() Option[V]

Last returns the last element from the sequence.

func (Seq[V]) Map added in v1.1.0

func (seq Seq[V]) Map[U any](transform func(V) U) Seq[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:

  • transform (func(V) U): The function used to transform elements. The result type may differ from the element type.

Returns:

- Seq[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().Slice()
strs.Print()

Output: Slice[2, 4, 6].

The resulting iterator will contain elements transformed by the provided function.

func (Seq[V]) MaxBy added in v1.1.0

func (seq Seq[V]) MaxBy(fn func(V, V) cmp.Ordering) Option[V]

MaxBy returns the maximum element in the sequence using the provided comparison function.

func (Seq[V]) MinBy added in v1.1.0

func (seq Seq[V]) MinBy(fn func(V, V) cmp.Ordering) Option[V]

MinBy returns the minimum element in the sequence using the provided comparison function.

func (*Seq[V]) Next added in v1.1.0

func (seq *Seq[V]) Next() Option[V]

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 (Seq[V]) Nth added in v1.1.0

func (seq Seq[V]) Nth(n Int) Option[V]

Nth returns the nth element (0-indexed) in the sequence.

func (Seq[V]) Partition added in v1.1.0

func (seq Seq[V]) Partition(fn func(v V) bool) (Slice[V], Slice[V])

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 (Seq[V]) Permutations added in v1.1.0

func (seq Seq[V]) Permutations() SeqSlices[V]

Permutations generates all permutations of the elements.

The function uses a recursive approach to generate all the permutations of the elements. If the iterator is empty, the resulting iterator is empty as well; a single-element iterator yields exactly one permutation.

Returns:

- SeqSlices[V]: An iterator yielding slices, each containing one permutation of the elements in the iterator.

Example usage:

slice := g.Slice[int]{1, 2, 3}
perms := slice.Iter().Permutations().Collect().Slices()
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 yield slices representing all possible permutations of the elements in the original iterator.

func (Seq[V]) ProductBy added in v1.1.0

func (seq Seq[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 (Seq[V]) Pull added in v1.1.0

func (seq Seq[V]) Pull() (func() (V, bool), func())

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 (Seq[V]) Range added in v1.1.0

func (seq Seq[V]) Range(fn func(v V) bool)

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()
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 (Seq[V]) Reduce added in v1.1.0

func (seq Seq[V]) Reduce(fn func(a, b V) V) Option[V]

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 (Seq[V]) Scan added in v1.1.0

func (seq Seq[V]) Scan[A any](init A, fn func(acc A, val V) A) Seq[A]

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:

- Seq[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 (Seq[V]) Skip added in v1.1.0

func (seq Seq[V]) Skip(n Int) Seq[V]

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 (Int): The number of elements to skip from the beginning of the iterator. Negative values are treated as zero.

Returns:

- Seq[V]: An iterator that starts after skipping the first n elements.

Example usage:

iter := g.Slice[int]{1, 2, 3, 4, 5, 6}.Iter()
iter.Skip(3).Collect().Slice().Print()

Output: [4, 5, 6]

The resulting iterator will start after skipping the specified number of elements.

func (Seq[V]) SkipWhile added in v1.1.0

func (seq Seq[V]) SkipWhile(fn func(V) bool) Seq[V]

SkipWhile skips elements while the predicate returns true, then yields the rest.

func (Seq[V]) SortBy added in v1.1.0

func (seq Seq[V]) SortBy(fn func(a, b V) cmp.Ordering) Seq[V]

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 a cmp.Ordering: cmp.Less orders 'a' before 'b', cmp.More after it.

Example:

g.SliceOf[g.String]("a", "c", "b").
	Iter().
	SortBy(func(a, b g.String) cmp.Ordering { return b.Cmp(a) }).
	Collect().
	Slice().
	Print()

Output: Slice[c, b, a]

The returned iterator is of type Seq[V], which implements the iterator interface for further iteration over the sorted elements.

func (Seq[V]) StepBy added in v1.1.0

func (seq Seq[V]) StepBy(n Int) Seq[V]

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: - Seq[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().Slice()
result.Print()

Output: Slice[1, 4, 7, 10]

The resulting iterator will produce elements from the original iterator with a step size of N.

func (Seq[V]) SumBy added in v1.1.0

func (seq Seq[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 (Seq[V]) Take added in v1.1.0

func (seq Seq[V]) Take(n Int) Seq[V]

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 (Seq[V]) TakeWhile added in v1.1.0

func (seq Seq[V]) TakeWhile(fn func(V) bool) Seq[V]

TakeWhile yields elements while the predicate returns true, stopping at the first false.

func (Seq[V]) TryMap added in v1.1.0

func (seq Seq[V]) TryMap[U any](fn func(V) Result[U]) SeqResult[U]

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 (Seq[V]) Unique added in v1.1.0

func (seq Seq[V]) Unique() Seq[V]

Unique returns an iterator with only unique elements.

The function returns an iterator containing only the unique elements from the original iterator.

Returns:

- Seq[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().Slice()
unique.Print()

Output: [1, 2, 3, 4, 5].

The resulting iterator will contain only unique elements from the original iterator.

func (Seq[V]) Windows added in v1.1.0

func (seq Seq[V]) Windows(n Int) SeqSlices[V]

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().Slices()

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.

func (Seq[V]) Zip added in v1.1.0

func (seq Seq[V]) Zip[U any](two Seq[U]) Seq2[V, U]

Zip combines elements from the current sequence and another sequence into pairs. The element types of the two sequences may differ. Iteration stops when either sequence is exhausted.

type Seq2 added in v1.1.0

type Seq2[K, V any] func(yield func(K, V) bool)

Seq2 is an iterator over sequences of ordered pairs of values, most commonly ordered key-value pairs.

func (Seq2[K, V]) All added in v1.1.0

func (seq Seq2[K, V]) All(fn func(K, V) bool) bool

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 (Seq2[K, V]) Any added in v1.1.0

func (seq Seq2[K, V]) Any(fn func(K, V) bool) bool

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 (Seq2[K, V]) Chain added in v1.1.0

func (seq Seq2[K, V]) Chain(seqs ...Seq2[K, V]) Seq2[K, V]

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 ([]Seq2[K, V]): Other iterators to be concatenated with the current iterator.

Returns:

- Seq2[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().MapOrd[int, string]().Print()

Output: MapOrd{1:a, 2:b}

The resulting iterator will contain elements from both iterators in the specified order.

func (Seq2[K, V]) Chan added in v1.1.0

func (seq Seq2[K, V]) Chan(ctxs ...context.Context) chan Pair[K, V]

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 (Seq2[K, V]) Collect added in v1.1.0

func (seq Seq2[K, V]) Collect() collector2[K, V]

Collect returns a collector over the key-value sequence. Collect itself is lazy and does not consume the sequence; only the collector's materializer methods do, turning the pairs into a concrete container:

m.Iter().FilterByKey(fn).Collect().Pairs()
m.Iter().FilterByKey(fn).Collect().Map[string, string]()
mo.Iter().Collect().MapOrd[string, string]()

func (Seq2[K, V]) Context added in v1.1.0

func (seq Seq2[K, V]) Context(ctx context.Context) Seq2[K, V]

Context allows the iteration to be controlled with a context.Context.

func (Seq2[K, V]) Count added in v1.1.0

func (seq Seq2[K, V]) Count() Int

Count consumes the iterator, counting the number of iterations and returning it.

func (Seq2[K, V]) Dedup added in v1.1.0

func (seq Seq2[K, V]) Dedup() Seq2[K, V]

Dedup returns a new iterator that removes consecutive pairs with duplicate keys, keeping the first pair of each run; values are not inspected. If the sequence is sorted by key, all keys will be unique. It mirrors Seq.Dedup, comparing keys with == when K is a comparable type and falling back to reflect.DeepEqual otherwise.

Example usage:

mo := g.MapOrd[g.Int, g.String]{{1, "a"}, {1, "b"}, {2, "c"}}
mo.Iter().Dedup().Collect().MapOrd[g.Int, g.String]().Print()

Output: MapOrd{1:a, 2:c}

func (Seq2[K, V]) Exclude added in v1.1.0

func (seq Seq2[K, V]) Exclude(fn func(K, V) bool) Seq2[K, V]

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:

- Seq2[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().MapOrd[int, int]()
notEven.Print()

Output: MapOrd{1:1, 3:3, 5:5}

The resulting iterator will exclude elements based on the provided condition.

func (Seq2[K, V]) Filter added in v1.1.0

func (seq Seq2[K, V]) Filter(fn func(K, V) bool) Seq2[K, V]

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:

- Seq2[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().MapOrd[int, int]()
even.Print()

Output: MapOrd{2:2, 4:4}

The resulting iterator will include elements based on the provided condition.

func (Seq2[K, V]) FilterByKey added in v1.1.0

func (seq Seq2[K, V]) FilterByKey(fn func(K) bool) Seq2[K, V]

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 (Seq2[K, V]) FilterByValue added in v1.1.0

func (seq Seq2[K, V]) FilterByValue(fn func(V) bool) Seq2[K, V]

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 (Seq2[K, V]) FilterMap added in v1.1.0

func (seq Seq2[K, V]) FilterMap[K2, V2 any](fn func(K, V) Option[Pair[K2, V2]]) Seq2[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 (Seq2[K, V]) Find added in v1.1.0

func (seq Seq2[K, V]) Find(fn func(k K, v V) bool) Option[Pair[K, V]]

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[Pair[K, V]]: An Option containing the first pair 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 (Seq2[K, V]) FindMap added in v1.1.0

func (seq Seq2[K, V]) FindMap[U any](fn func(K, V) Option[U]) Option[U]

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 (Seq2[K, V]) First added in v1.1.0

func (seq Seq2[K, V]) First() Option[Pair[K, V]]

First returns the first key-value pair from the sequence.

func (Seq2[K, V]) Fold added in v1.1.0

func (seq Seq2[K, V]) Fold[A any](init A, fn func(acc A, k K, v V) A) A

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 (Seq2[K, V]) ForEach added in v1.1.0

func (seq Seq2[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, val int) {
    // Process key-value pair
})

The provided function will be applied to each key-value pair in the iterator.

func (Seq2[K, V]) Inspect added in v1.1.0

func (seq Seq2[K, V]) Inspect(fn func(k K, v V)) Seq2[K, V]

Inspect creates a new iterator that wraps around the current iterator and allows inspecting each key-value pair as it passes through.

func (Seq2[K, V]) Intersperse added in v1.1.0

func (seq Seq2[K, V]) Intersperse(sep Pair[K, V]) Seq2[K, V]

Intersperse inserts the provided separator pair between each consecutive pair of elements in the original iterator, mirroring Seq.Intersperse.

func (Seq2[K, V]) Keys added in v1.1.0

func (seq Seq2[K, V]) Keys() Seq[K]

Keys returns an iterator over the keys of the key-value pairs.

func (Seq2[K, V]) Last added in v1.1.0

func (seq Seq2[K, V]) Last() Option[Pair[K, V]]

Last returns the last key-value pair from the sequence.

func (Seq2[K, V]) Map added in v1.1.0

func (seq Seq2[K, V]) Map[K2, V2 any](transform func(K, V) (K2, V2)) Seq2[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:

- transform (func(K, V) (K2, V2)): The function used to transform each key-value pair in the iterator. The key and value types of the result may differ.

Returns:

- Seq2[K2, V2]: 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().MapOrd[int, int]()

momap.Print()

Output: MapOrd{1:1, 4:4, 9:9, 16:16, 25:25}

The resulting iterator will contain transformed key-value pairs.

func (Seq2[K, V]) MapTo added in v1.1.0

func (seq Seq2[K, V]) MapTo[T any](fn func(K, V) T) Seq[T]

MapTo transforms each pair into a single value using the given function, returning a value sequence of the results. It complements Seq2.Map, which keeps the pair shape.

func (Seq2[K, V]) MaxBy added in v1.1.0

func (seq Seq2[K, V]) MaxBy(fn func(a, b Pair[K, V]) cmp.Ordering) Option[Pair[K, V]]

MaxBy returns the maximum pair in the sequence using the provided comparison function, mirroring Seq.MaxBy. It returns None if the sequence is empty.

func (Seq2[K, V]) MinBy added in v1.1.0

func (seq Seq2[K, V]) MinBy(fn func(a, b Pair[K, V]) cmp.Ordering) Option[Pair[K, V]]

MinBy returns the minimum pair in the sequence using the provided comparison function, mirroring Seq.MinBy. It returns None if the sequence is empty.

func (*Seq2[K, V]) Next added in v1.1.0

func (seq *Seq2[K, V]) Next() Option[Pair[K, V]]

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 (Seq2[K, V]) Nth added in v1.1.0

func (seq Seq2[K, V]) Nth(n Int) Option[Pair[K, V]]

Nth returns the nth key-value pair (0-indexed) in the sequence.

func (Seq2[K, V]) ProductBy added in v1.1.0

func (seq Seq2[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 (Seq2[K, V]) Pull added in v1.1.0

func (seq Seq2[K, V]) Pull() (func() (K, V, bool), func())

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 (Seq2[K, V]) Range added in v1.1.0

func (seq Seq2[K, V]) Range(fn func(k K, v V) bool)

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 (Seq2[K, V]) Reduce added in v1.1.0

func (seq Seq2[K, V]) Reduce(fn func(a, b Pair[K, V]) Pair[K, V]) Option[Pair[K, V]]

Reduce aggregates the pairs of the sequence using the provided function, mirroring Seq.Reduce. The first pair is used as the initial accumulator value. It returns None if the sequence is empty.

func (Seq2[K, V]) Scan added in v1.1.0

func (seq Seq2[K, V]) Scan[A any](init A, fn func(acc A, k K, v V) A) Seq[A]

Scan accumulates the pairs of the sequence using a function, yielding the initial value followed by each intermediate accumulator state, mirroring Seq.Scan. The accumulator type may differ from the key and value types.

Example usage:

mo := g.MapOrd[g.String, g.Int]{{"a", 1}, {"b", 2}, {"c", 3}}
sums := mo.Iter().Scan(0, func(acc int, _ g.String, v g.Int) int {
	return acc + int(v)
})
// sums will yield: 0, 1, 3, 6

func (Seq2[K, V]) Skip added in v1.1.0

func (seq Seq2[K, V]) Skip(n Int) Seq2[K, V]

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 (Int): The number of elements to skip from the beginning of the iterator. Negative values are treated as zero.

Returns:

- Seq2[K, V]: An iterator that starts after skipping the first n elements.

Example usage:

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().MapOrd[int, string]().Print()

Output: MapOrd{3:c, 4:d}

The resulting iterator will start after skipping the specified number of elements.

func (Seq2[K, V]) SkipWhile added in v1.1.0

func (seq Seq2[K, V]) SkipWhile(fn func(K, V) bool) Seq2[K, V]

SkipWhile skips key-value pairs while the predicate returns true, then yields the rest.

func (Seq2[K, V]) SortBy added in v1.1.0

func (seq Seq2[K, V]) SortBy(fn func(a, b Pair[K, V]) cmp.Ordering) Seq2[K, V]

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 a cmp.Ordering: cmp.Less orders 'a' before 'b', cmp.More after it.

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().
	MapOrd[g.Int, g.String]().
	Print()

Output: MapOrd{0:dd, 1:aa, 2:cc, 3:ff, 4:zz, 5:xx, 6:bb}

The returned iterator is of type Seq2[K, V], which implements the iterator interface for further iteration over the sorted elements.

func (Seq2[K, V]) SortByKey added in v1.1.0

func (seq Seq2[K, V]) SortByKey(fn func(a, b K) cmp.Ordering) Seq2[K, V]

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 a cmp.Ordering: cmp.Less orders 'a' before 'b', cmp.More after it.

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().
	MapOrd[g.Int, g.String]().
	Print()

Output: MapOrd{0:dd, 1:aa, 2:cc, 3:ff, 4:zz, 5:xx, 6:bb}

func (Seq2[K, V]) SortByValue added in v1.1.0

func (seq Seq2[K, V]) SortByValue(fn func(a, b V) cmp.Ordering) Seq2[K, V]

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 a cmp.Ordering: cmp.Less orders 'a' before 'b', cmp.More after it.

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().
	MapOrd[g.Int, g.String]().
	Print()

Output: MapOrd{1:aa, 6:bb, 2:cc, 0:dd, 3:ff, 5:xx, 4:zz}

func (Seq2[K, V]) StepBy added in v1.1.0

func (seq Seq2[K, V]) StepBy(n Int) Seq2[K, V]

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: - Seq2[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)
iter.Collect().MapOrd[string, int]().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 (Seq2[K, V]) SumBy added in v1.1.0

func (seq Seq2[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 (Seq2[K, V]) Take added in v1.1.0

func (seq Seq2[K, V]) Take(n Int) Seq2[K, V]

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 (Seq2[K, V]) TakeWhile added in v1.1.0

func (seq Seq2[K, V]) TakeWhile(fn func(K, V) bool) Seq2[K, V]

TakeWhile yields key-value pairs while the predicate returns true, stopping at the first false.

func (Seq2[K, V]) TryMap added in v1.1.0

func (seq Seq2[K, V]) TryMap[U any](fn func(K, V) Result[U]) SeqResult[U]

TryMap applies a fallible transform to each key-value pair and enters the Result pipeline, producing a SeqResult[U]. See Seq.TryMap for the full contract.

func (Seq2[K, V]) Unique added in v1.1.0

func (seq Seq2[K, V]) Unique() Seq2[K, V]

Unique returns a new iterator yielding only the first pair for each distinct key; later pairs with an already-seen key are dropped and values are not inspected. It mirrors Seq.Unique. The keys are tracked in a map, so a key type that is not hashable at runtime (e.g. a slice, map, function, or a struct containing one) panics with "hash of unhashable type".

Example usage:

mo := g.MapOrd[g.Int, g.String]{{1, "a"}, {2, "b"}, {1, "c"}}
mo.Iter().Unique().Collect().MapOrd[g.Int, g.String]().Print()

Output: MapOrd{1:a, 2:b}

func (Seq2[K, V]) Unzip added in v1.1.0

func (seq Seq2[K, V]) Unzip() (Slice[K], Slice[V])

Unzip consumes the sequence and collects the keys and values of each pair into two separate slices.

func (Seq2[K, V]) Values added in v1.1.0

func (seq Seq2[K, V]) Values() Seq[V]

Values returns an iterator over the values of the key-value pairs.

type SeqResult added in v1.0.115

type SeqResult[V any] func(yield func(Result[V]) bool)

SeqResult is an iterator over sequences of Result[V] values.

func ErrSeq added in v1.0.222

func ErrSeq[V any](err error) SeqResult[V]

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

func FromResultChan[V any](ch <-chan Result[V]) SeqResult[V]

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:

p := pool.New[int]().Limit(10)
ch := p.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

func OkSeq[V any](v V) SeqResult[V]

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

func (seq SeqResult[V]) All(fn func(v V) bool) Result[bool]

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

func (seq SeqResult[V]) Any(fn func(v V) bool) Result[bool]

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

func (seq SeqResult[V]) Chain(seqs ...SeqResult[V]) SeqResult[V]

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

func (seq SeqResult[V]) Collect() collector[Result[V]]

Collect returns a collector over the raw Result elements, matching the Seq/Seq2 collector idiom: materialize with .Slice() (etc.). Collect itself is lazy and does not consume the sequence; the materializer does. Both Ok and Err elements flow through as-is; encountering an Err does not stop collection. Use TryCollect for the short-circuiting Ok-only variant.

func (SeqResult[V]) Context added in v1.0.181

func (seq SeqResult[V]) Context(ctx context.Context) SeqResult[V]

Context allows the iteration to be controlled with a context.Context.

func (SeqResult[V]) Count added in v1.0.116

func (seq SeqResult[V]) Count() Int

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[[]Pair[K, Int]]

CounterBy counts how many Ok values map to each key produced by fn, returning the tally as plain pairs in first-seen key order (convert with MapOrd[K, Int] if map access is needed). 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; returning MapOrd would weld SeqResult to the map cluster.)

func (SeqResult[V]) Dedup added in v1.0.115

func (seq SeqResult[V]) Dedup() SeqResult[V]

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

func (seq SeqResult[V]) Err() Seq[error]

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

func (seq SeqResult[V]) Exclude(fn func(V) bool) SeqResult[V]

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

func (seq SeqResult[V]) Filter(fn func(V) bool) SeqResult[V]

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

func (seq SeqResult[V]) FilterMap[U any](fn func(V) Option[U]) SeqResult[U]

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

func (seq SeqResult[V]) Find(fn func(V) bool) Result[Option[V]]

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

func (seq SeqResult[V]) FindMap[U any](fn func(V) Option[U]) Result[Option[U]]

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

func (seq SeqResult[V]) First() Result[Option[V]]

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

func (seq SeqResult[V]) FirstErr() Option[error]

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

func (seq SeqResult[V]) FlatMap[U any](fn func(V) Seq[U]) SeqResult[U]

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

func (seq SeqResult[V]) Flatten() SeqResult[V]

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 Seq.Flatten and, like it, relies on reflection: only leaves assignable to V are yielded.

func (SeqResult[V]) Fold added in v1.0.228

func (seq SeqResult[V]) Fold[A any](init A, fn func(acc A, val V) A) Result[A]

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

func (seq SeqResult[V]) ForEach(fn func(v Result[V]))

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

func (seq SeqResult[V]) Inspect(fn func(v V)) SeqResult[V]

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

func (seq SeqResult[V]) Intersperse(sep V) SeqResult[V]

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

func (seq SeqResult[V]) Last() Result[Option[V]]

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

func (seq SeqResult[V]) Map[U any](transform func(V) U) SeqResult[U]

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

func (seq SeqResult[V]) MaxBy(fn func(V, V) cmp.Ordering) Result[Option[V]]

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

func (seq SeqResult[V]) MinBy(fn func(V, V) cmp.Ordering) Result[Option[V]]

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

func (seq *SeqResult[V]) Next() Option[Result[V]]

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

func (seq SeqResult[V]) Nth(n Int) Result[Option[V]]

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

func (seq SeqResult[V]) Ok() Seq[V]

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

func (seq SeqResult[V]) Partition() (Slice[V], Slice[error])

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

func (seq SeqResult[V]) Pull() (func() (Result[V], bool), func())

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

func (seq SeqResult[V]) Range(fn func(v Result[V]) bool)

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

func (seq SeqResult[V]) Reduce(fn func(a, b V) V) Result[Option[V]]

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

func (seq SeqResult[V]) Scan[A any](init A, fn func(acc A, val V) A) SeqResult[A]

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

func (seq SeqResult[V]) Skip(n Int) SeqResult[V]

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

func (seq SeqResult[V]) SkipWhile(fn func(V) bool) SeqResult[V]

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

func (seq SeqResult[V]) SortBy(fn func(a, b V) cmp.Ordering) SeqResult[V]

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

func (seq SeqResult[V]) StepBy(n Int) SeqResult[V]

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

func (seq SeqResult[V]) Take(n Int) SeqResult[V]

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

func (seq SeqResult[V]) TakeWhile(fn func(V) bool) SeqResult[V]

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

func (seq SeqResult[V]) TryCollect() Result[Slice[V]]

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.

func (SeqResult[V]) Unique added in v1.0.115

func (seq SeqResult[V]) Unique() SeqResult[V]

Unique returns a new sequence that contains only the first occurrence of each distinct Ok value.

If an Err is encountered, it is yielded downstream as-is (consumer-driven). Future occurrences of a previously seen Ok value are skipped.

type SeqSlices added in v1.0.63

type SeqSlices[V any] func(yield func([]V) bool)

SeqSlices is an iterator over slices of sequences of individual values.

It is a distinct named type rather than Seq[[]V]: a named Seq[[]V] mentioned from Seq[V]'s method set (Chunks, Windows, ChunkBy, Combinations, Permutations) would be an instantiation cycle the compiler rejects.

func (SeqSlices[V]) Collect added in v1.0.63

func (seqs SeqSlices[V]) Collect() collectorS[V]

Collect returns a collector over the grouped sequence; its Slices method materializes the groups. Collect itself is lazy and does not consume the sequence.

func (SeqSlices[V]) Filter added in v1.0.225

func (seqs SeqSlices[V]) Filter(fn func(Slice[V]) bool) SeqSlices[V]

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().Slices()

func (SeqSlices[V]) Flatten added in v1.0.225

func (seqs SeqSlices[V]) Flatten() Seq[V]

Flatten flattens the iterator of groups (sub-slices) into a single Seq[V], yielding the elements of each group in order.

Returns:

- Seq[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().Slice()
// Output: Slice[1, 2, 3, 4, 5, 6]

func (SeqSlices[V]) ForEach added in v1.0.225

func (seqs SeqSlices[V]) ForEach(fn func(s Slice[V]))

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

func (seqs SeqSlices[V]) Map[U any](fn func(Slice[V]) Slice[U]) SeqSlices[U]

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[U]): The function used to transform each group. The element type of the resulting groups may differ.

Returns:

- SeqSlices[U]: 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().Slice()
	}).
	Collect().Slices()
// 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 SetOf

func SetOf[T comparable](values ...T) Set[T]

SetOf creates a new generic set containing the provided elements.

func (Set[T]) Clear

func (s Set[T]) Clear()

Clear removes all values from the Set.

func (Set[T]) Clone

func (s Set[T]) Clone() Set[T]

Clone creates a new Set that is a copy of the original Set.

func (Set[T]) Contains

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

Contains checks if the Set contains the specified value.

func (Set[T]) ContainsAll

func (s Set[T]) ContainsAll(values ...T) bool

ContainsAll checks if the Set contains all of the provided values, matching the variadic shape of Slice.ContainsAll and String.ContainsAll.

func (Set[T]) ContainsAny

func (s Set[T]) ContainsAny(values ...T) bool

ContainsAny checks if the Set contains any of the provided values, matching the variadic shape of Slice.ContainsAny and String.ContainsAny.

func (Set[T]) Difference

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

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

func (s Set[T]) Disjoint(other Set[T]) bool

Disjoint reports whether the set has no elements in common with other. It is the complement of ContainsAny.

func (Set[T]) Eq

func (s Set[T]) Eq(other Set[T]) bool

Eq checks if two Sets are equal.

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

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

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]) IsEmpty added in v1.0.202

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

IsEmpty checks if the Set is empty.

func (Set[T]) Iter

func (s Set[T]) Iter() Seq[T]

Iter returns an iterator (Seq[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 'Map', to perform operations on each element of the Set.

Returns:

A Seq[T], which can be used for sequential iteration over the elements of the Set.

Example usage:

g.SetOf(1, 2, 3).Iter().ForEach(func(val int) {
    fmt.Println(val) // Replace this with the function logic you need.
})

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]) Len

func (s Set[T]) Len() Int

Len returns the number of values in the Set.

func (Set[T]) Ne

func (s Set[T]) Ne(other Set[T]) bool

Ne checks if two Sets are not equal.

func (Set[T]) Print

func (s Set[T]) Print() Set[T]

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

func (s Set[T]) Println() Set[T]

Println writes the elements of the Set to the standard output (console) with a newline and returns the Set unchanged.

func (Set[T]) Remove

func (s Set[T]) Remove(v T) bool

Remove removes the specified value from the Set and returns true if it was present.

func (Set[T]) String

func (s Set[T]) String() string

String returns a string representation of the Set.

func (Set[T]) Subset

func (s Set[T]) Subset(other Set[T]) bool

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

func (s Set[T]) Superset(other Set[T]) bool

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

func (s Set[T]) SymmetricDifference(other Set[T]) Set[T]

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

func (s Set[T]) Transform[U any](fn func(Set[T]) U) U

Transform applies a transformation function to the Set and returns the result.

func (Set[T]) Union

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

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

func NewSlice[T any](size ...Int) Slice[T]

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 SliceOf

func SliceOf[T any](slice ...T) Slice[T]

SliceOf creates a new generic slice containing the provided elements.

func TransformSlice added in v1.0.89

func TransformSlice[T, U any](sl []T, fn func(T) U) Slice[U]

TransformSlice maps a plain Go slice into a Slice through fn. It is the exported bridge between stdlib-shaped results and g containers, shared with the subpackages (rx uses it for its match groups).

func (Slice[T]) Append

func (sl Slice[T]) Append(elems ...T) Slice[T]

Append appends the provided elements to the slice and returns the modified slice.

func (Slice[T]) AppendUnique added in v1.0.143

func (sl Slice[T]) AppendUnique(elems ...T) Slice[T]

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

func (sl Slice[T]) BinarySearch(value T, fn func(a, b T) cmp.Ordering) Option[Int]

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]) Cap

func (sl Slice[T]) Cap() Int

Cap returns the capacity of the Slice.

func (Slice[T]) Clip

func (sl Slice[T]) Clip() Slice[T]

Clip removes unused capacity from the slice.

func (Slice[T]) Clone

func (sl Slice[T]) Clone() Slice[T]

Clone returns a copy of the slice.

func (Slice[T]) Contains

func (sl Slice[T]) Contains(val T) bool

Contains returns true if the slice contains the provided value.

func (Slice[T]) ContainsAll

func (sl Slice[T]) ContainsAll(values ...T) bool

ContainsAll checks if the Slice contains all elements from another Slice.

func (Slice[T]) ContainsAny

func (sl Slice[T]) ContainsAny(values ...T) bool

ContainsAny checks if the Slice contains any element from another Slice.

func (Slice[T]) ContainsBy added in v1.0.65

func (sl Slice[T]) ContainsBy(fn func(t T) bool) bool

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

func (sl *Slice[T]) DedupBy(eq func(a, b T) bool)

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 Seq.Dedup. Only adjacent duplicates are removed, so sort first for a global dedup.

func (Slice[T]) Eq

func (sl Slice[T]) Eq(other Slice[T]) bool

Eq returns true if the slice is equal to the provided other slice.

func (Slice[T]) EqBy added in v1.0.65

func (sl Slice[T]) EqBy(other Slice[T], fn func(x, y T) bool) bool

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.

Example usage:

slice := g.Slice[int]{0, 0, 0}
slice.Fill(5)

The modified slice will now contain: 5, 5, 5.

func (Slice[T]) First added in v1.0.202

func (sl Slice[T]) First() Option[T]

First returns the first element of the slice.

func (Slice[T]) Get

func (sl Slice[T]) Get(index Int) Option[T]

Get returns the element at the given index, handling negative indices as counting from the end of the slice.

func (Slice[T]) Grow

func (sl Slice[T]) Grow(n Int) Slice[T]

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]) Index

func (sl Slice[T]) Index(val T) Int

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

func (sl Slice[T]) IndexBy(fn func(t T) bool) Int

IndexBy returns the index of the first element in the slice satisfying the predicate function provided by the user. It iterates through the slice and applies the predicate to each element. If the predicate returns true for an element, it returns the index of that element. If no such element is found, it returns -1.

func (*Slice[T]) Insert

func (sl *Slice[T]) Insert(i Int, values ...T)

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]) IsEmpty added in v1.0.202

func (sl Slice[T]) IsEmpty() bool

IsEmpty returns true if the slice is empty.

func (Slice[T]) IsSortedBy added in v1.0.193

func (sl Slice[T]) IsSortedBy(fn func(a, b T) cmp.Ordering) bool

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

func (sl Slice[T]) Iter() Seq[T]

Iter returns an iterator (Seq[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 Seq[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

func (sl Slice[T]) IterReverse() Seq[T]

IterReverse returns an iterator (Seq[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 Seq[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

func (sl Slice[T]) Join(sep ...T) String

Join joins the elements in the slice into a single String, separated by the provided separator (if any).

func (Slice[T]) Last

func (sl Slice[T]) Last() Option[T]

Last returns the last element of the slice.

func (Slice[T]) LastIndex

func (sl Slice[T]) LastIndex() Int

LastIndex returns the last index of the slice.

func (Slice[T]) Len

func (sl Slice[T]) Len() Int

Len returns the length of the slice.

func (Slice[T]) Ne

func (sl Slice[T]) Ne(other Slice[T]) bool

Ne returns true if the slice is not equal to the provided other slice.

func (Slice[T]) NeBy added in v1.0.68

func (sl Slice[T]) NeBy(other Slice[T], fn func(x, y T) bool) bool

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

func (sl Slice[T]) PartitionPoint(pred func(T) bool) Int

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

func (sl *Slice[T]) Pop() Option[T]

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

func (sl Slice[T]) Print() Slice[T]

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

func (sl Slice[T]) Println() Slice[T]

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]) Remove added in v1.0.202

func (sl *Slice[T]) Remove(index Int) Option[T]

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

func (sl *Slice[T]) Replace(i, j Int, values ...T)

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

func (sl *Slice[T]) Retain(fn func(T) bool)

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.

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

func (sl Slice[T]) Set(index Int, val T) Option[T]

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]) SortBy

func (sl Slice[T]) SortBy(fn func(a, b T) cmp.Ordering)

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]) String

func (sl Slice[T]) String() string

String returns a string representation of the slice.

func (Slice[T]) SubSlice

func (sl Slice[T]) SubSlice(start, end Int, step ...Int) Slice[T]

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

func (sl Slice[T]) Swap(i, j Int)

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.

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

func (sl Slice[T]) Transform[U any](fn func(Slice[T]) U) U

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 a wrapper around the string type.

func Format

func Format[T ~string](template T, args ...any) String

Format processes a template string and replaces placeholders with corresponding values from the provided arguments. It supports numeric, named, and auto-indexed placeholders, with dot-access into map keys, slice/array indices, and struct fields.

If a placeholder cannot resolve a value, it 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.field}`, `{key.0}` - References keys from a `Named` map with data access into struct fields, map/MapOrd keys, and slice indices (methods are never invoked).
  • Fallback: `{key?fallback}` - If `key` is not found in the named map, uses the value of the named key `fallback` instead (not the literal text).
  • Auto-index: `{}` - Automatically uses the next positional argument if the placeholder is empty.
  • Escaping: `{{` and `}}` - Emits literal braces.

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.
  • Dot-segments access data only (struct fields, map keys, MapOrd keys, slice/array indices); methods are never invoked. An unresolvable segment leaves the value 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:

  • Placeholders resolve data only: map keys, MapOrd keys, slice/array indices, and struct fields. Methods are never invoked, so a template cannot execute code on the supplied arguments.

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: Field/key access
type User struct{ Name g.String }
user := User{Name: "Alice"}
result := g.Format("Name: {1.Name}", user)

// Example 4: Fallbacks
named := g.Named{
	"name": g.String("John"),
	"city": g.String("New York"),
}
result := g.Format("Hello, {name}. Welcome to {city?Unknown}!", named)

func NewString

func NewString[T ~string | rune | byte | ~[]rune | ~[]byte](str T) String

NewString creates a new String from the provided string, rune, byte, rune slice, or byte slice.

func (String) Append added in v1.0.62

func (s String) Append(str String) String

Append appends the specified String to the current String.

func (String) Builder added in v1.0.62

func (s String) Builder() *Builder

Builder returns a new Builder initialized with the content of the String.

func (String) Bytes added in v1.0.81

func (s String) Bytes() Bytes

Bytes returns the String as an Bytes.

func (String) BytesUnsafe added in v1.0.147

func (s String) BytesUnsafe() Bytes

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

func (s String) Center(length Int, pad String) String

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

func (s String) Chars() []String

Chars splits the String into individual UTF-8 characters, equivalent to s.Split(""). Prefer Runes when only code points are needed.

func (String) Chunks

func (s String) Chunks(size Int) []String

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 nil. If size is greater than or equal to the length of the String, it returns the original String as the only chunk.

Parameters:

- size (Int): The size of the chunks to split the String into.

Returns:

- []String: the 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

func (s String) Clone() String

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

func (s String) Cmp(str String) cmp.Ordering

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) Contains

func (s String) Contains(substr String) bool

Contains checks if the String contains the specified substring.

func (String) ContainsAll

func (s String) ContainsAll(substrs ...String) bool

ContainsAll checks if the given String contains all the specified substrings.

func (String) ContainsAny

func (s String) ContainsAny(substrs ...String) bool

ContainsAny checks if the String contains any of the specified substrings.

func (String) ContainsAnyChars

func (s String) ContainsAnyChars(chars String) bool

ContainsAnyChars checks if the String contains any characters from the specified String.

func (String) ContainsRune

func (s String) ContainsRune(r rune) bool

ContainsRune checks if the String contains the specified rune.

func (String) Count

func (s String) Count(substr String) Int

Count returns the number of non-overlapping instances of the substring in the String.

func (String) Cut

func (s String) Cut(start, end String, rmtags ...bool) (String, String)

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 first String, and an empty String as the second.

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 the original 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 an empty 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) EndsWith

func (s String) EndsWith(suffix String) bool

EndsWith checks if the String ends with the specified suffix.

func (String) EndsWithAny added in v1.0.90

func (s String) EndsWithAny(suffixes ...String) bool

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) Eq

func (s String) Eq(str String) bool

Eq checks if two Strings are equal.

func (String) EqFold

func (s String) EqFold(str String) bool

EqFold compares two String strings case-insensitively.

func (String) Fields

func (s String) Fields() []String

Fields splits the String around whitespace. See String.Lines for why the return type is a plain slice.

func (String) FieldsBy added in v1.0.76

func (s String) FieldsBy(fn func(r rune) bool) []String

FieldsBy splits the String using a custom function to determine the field boundaries. See String.Lines for why the return type is a plain slice.

func (String) Format

func (s String) Format(template String) String

Format applies a specified format to the String object.

func (String) Gt

func (s String) Gt(str String) bool

Gt checks if the String is greater than the specified String.

func (String) Gte added in v1.0.76

func (s String) Gte(str String) bool

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

func (s String) Index(substr String) Int

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) IndexByte added in v1.1.0

func (s String) IndexByte(b byte) Int

IndexByte returns the index of the first instance of the specified byte in the String, or -1 if b is not present in s.

func (String) IndexRune

func (s String) IndexRune(r rune) Int

IndexRune returns the index of the first instance of the specified rune in the String.

func (String) IsASCII

func (s String) IsASCII() bool

IsASCII checks if all characters in the String are ASCII bytes.

func (String) IsDigit

func (s String) IsDigit() bool

IsDigit checks if all characters in the String are digits.

func (String) IsEmpty added in v1.0.202

func (s String) IsEmpty() bool

IsEmpty checks if the String is empty.

func (String) IsLower added in v1.0.195

func (s String) IsLower() bool

IsLower checks if the String consists only of lowercase letters.

func (String) IsTitle added in v1.0.213

func (s String) IsTitle() bool

IsTitle checks if the String is in title case.

func (String) IsUpper added in v1.0.195

func (s String) IsUpper() bool

IsUpper checks if the String consists only of uppercase letters.

func (String) LastIndex

func (s String) LastIndex(substr String) Int

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) LastIndexByte added in v1.1.0

func (s String) LastIndexByte(b byte) Int

LastIndexByte returns the index of the last instance of the specified byte in the String, or -1 if b is not present in s.

func (String) LeftJustify

func (s String) LeftJustify(length Int, pad String) String

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) Len

func (s String) Len() Int

Len returns the length of the String.

func (String) LenRunes

func (s String) LenRunes() Int

LenRunes returns the number of runes in the String.

func (String) Lines added in v1.0.76

func (s String) Lines() []String

Lines splits the String by lines, with trailing whitespace trimmed per line. The substrings share the receiver's backing memory.

It returns a plain []String — deliberately not a Seq or Slice: a named generic type in the signature would make every package that names g.String compile the whole container machinery. Convert with g.SliceOf(parts...) for chaining; for lazy streaming over files use fs.File.Lines.

func (String) Lower

func (s String) Lower() String

Lower returns the String in lowercase.

func (String) Lt

func (s String) Lt(str String) bool

Lt checks if the String is less than the specified String.

func (String) Lte added in v1.0.76

func (s String) Lte(str String) bool

Lte checks if the String is less than or equal to the specified String.

func (String) Map

func (s String) Map(fn func(rune) rune) String

Map applies the provided function to all runes in the String and returns the resulting String.

func (String) Max

func (s String) Max(b ...String) String

Max returns the maximum of Strings.

func (String) Min

func (s String) Min(b ...String) String

Min returns the minimum of Strings.

func (String) Ne

func (s String) Ne(str String) bool

Ne checks if two Strings are not equal.

func (String) NormalizeNFC

func (s String) NormalizeNFC() String

NormalizeNFC returns a new String with its Unicode characters normalized using the NFC form.

func (String) Prepend added in v1.0.62

func (s String) Prepend(str String) String

Prepend prepends the specified String to the current String.

func (String) Print

func (s String) Print() String

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

func (s String) Println() String

Println writes the content of the String to the standard output (console) with a newline and returns the String unchanged.

func (String) Reader

func (s String) Reader() *strings.Reader

Reader returns a *strings.Reader initialized with the content of String.

func (String) Remove added in v1.0.78

func (s String) Remove(matches ...String) String

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

func (s String) Repeat(count Int) String

Repeat returns a new String consisting of the specified count of the original String.

func (String) Replace

func (s String) Replace(oldS, newS String, n Int) String

Replace replaces the 'oldS' String with the 'newS' String for the specified number of occurrences.

func (String) ReplaceAll

func (s String) ReplaceAll(oldS, newS String) String

ReplaceAll replaces all occurrences of the 'oldS' String with the 'newS' String.

func (String) ReplaceMulti

func (s String) ReplaceMulti(oldnew ...String) String

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 a example."

func (String) ReplaceNth

func (s String) ReplaceNth(oldS, newS String, n Int) String

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) Reverse

func (s String) Reverse() String

Reverse reverses the String.

func (String) RightJustify

func (s String) RightJustify(length Int, pad String) String

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) Runes added in v1.0.81

func (s String) Runes() []rune

Runes returns the String as a plain slice of runes.

func (*String) Scan added in v1.0.198

func (s *String) Scan(src any) error

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

func (s String) Similarity(str String) Float

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

func (s String) Split(sep String) []String

Split splits the String by the specified separator. If sep is empty, the String is split after each UTF-8 rune. See String.Lines for why the return type is a plain slice.

func (String) SplitAfter added in v1.0.76

func (s String) SplitAfter(sep String) []String

SplitAfter splits the String after each instance of the specified separator. See String.Lines for why the return type is a plain slice.

func (String) SplitN

func (s String) SplitN(sep String, n Int) []String

SplitN splits the String into substrings using the provided separator and returns a plain []String of the results (convert with Slice[String] for chaining). 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 is returned. - If n is positive, at most n substrings are returned.

func (String) StartsWith

func (s String) StartsWith(prefix String) bool

StartsWith checks if the String starts with the specified prefix.

func (String) StartsWithAny added in v1.0.90

func (s String) StartsWithAny(prefixes ...String) bool

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) Std

func (s String) Std() string

Std returns the String as a string.

func (String) StripPrefix added in v1.0.81

func (s String) StripPrefix(prefix String) String

StripPrefix trims the specified prefix from the String.

func (String) StripSuffix added in v1.0.81

func (s String) StripSuffix(suffix String) String

StripSuffix trims the specified suffix from the String.

func (String) SubString added in v1.0.127

func (s String) SubString(start, end Int, step ...Int) String

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) Title

func (s String) Title() String

Title converts the String to title case.

func (String) Transform added in v1.0.89

func (s String) Transform[U any](fn func(String) U) U

Transform applies a transformation function to the String and returns the result.

func (String) Trim

func (s String) Trim() String

Trim removes leading and trailing white space from the String.

func (String) TrimEnd added in v1.0.81

func (s String) TrimEnd() String

TrimEnd removes trailing white space from the String.

func (String) TrimEndSet added in v1.0.82

func (s String) TrimEndSet(cutset String) String

TrimEndSet removes the specified set of characters from the end of the String.

func (String) TrimSet added in v1.0.82

func (s String) TrimSet(cutset String) String

TrimSet removes the specified set of characters from both the beginning and end of the String.

func (String) TrimStart added in v1.0.81

func (s String) TrimStart() String

TrimStart removes leading white space from the String.

func (String) TrimStartSet added in v1.0.82

func (s String) TrimStartSet(cutset String) String

TrimStartSet removes the specified set of characters from the beginning of the String.

func (String) Truncate added in v1.0.126

func (s String) Truncate(max Int) String

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

func (s String) TryBigInt() Result[*big.Int]

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

func (s String) TryBool() Result[bool]

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

func (s String) TryFloat() Result[Float]

TryFloat tries to parse the String as a float64 and returns an Float.

func (String) TryInt added in v1.0.205

func (s String) TryInt() Result[Int]

TryInt tries to parse the String as an int and returns an Int.

func (String) TryUint added in v1.0.228

func (s String) TryUint() Result[uint]

TryUint tries to parse the String as an unsigned integer and returns a uint. The base is inferred from the prefix (0x, 0o/0, 0b), matching TryInt.

func (String) Upper

func (s String) Upper() String

Upper returns the String in uppercase.

func (String) Value added in v1.0.198

func (s String) Value() (driver.Value, error)

Value implements the database/sql/driver.Valuer interface for g.String.

Behavior:

  • Returns the underlying string value, ready for database insertion.
  • Always returns a value compatible with SQL TEXT / VARCHAR types.

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.

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
cmp command
deque command
dirs/dirs_copy command
dirs/dirs_iter command
dirs/dirs_walk command
entry command
files/file_iter command
files/files command
files/tmp_file command
floats command
heap command
ints command
iter/iter_any command
iter/iter_chain command
iter/iter_count command
iter/iter_dedup command
iter/iter_find command
iter/iter_fold command
iter/iter_map command
iter/iter_next 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_zip command
main command
map command
maps_ordered command
monads/option command
monads/result command
mutex command
pool/pool command
pool/pool_perf command
prime command
print command
print/basic command
print/errorf command
print/format command
range command
rwlock command
sets command
slices/slices command
strings command
strings_builder command
strings_regexp command
f
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.
Package fs provides chainable, Result-based filesystem operations (File, Dir), including lazy SeqResult iterators over file lines and chunks.
Package fs provides chainable, Result-based filesystem operations (File, Dir), including lazy SeqResult iterators over file lines and chunks.
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.
mimesniff
Package mimesniff is a verbatim copy of the Go standard library's content sniffer (`net/http/internal/sniff.go`), reproduced here under the Go BSD-3 licence; see the Go Authors copyright header at the top of this file.
Package mimesniff is a verbatim copy of the Go standard library's content sniffer (`net/http/internal/sniff.go`), reproduced here under the Go BSD-3 licence; see the Go Authors copyright header at the top of this file.
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 rand is the single home for randomness over g types, built on math/rand/v2.
Package rand is the single home for randomness over g types, built on math/rand/v2.
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.
Package rx provides compiled regular expressions: compile a pattern once with New, then run it against g.String haystacks (or g.Bytes via the *Bytes method variants).
Package rx provides compiled regular expressions: compile a pattern once with New, then run it against g.String haystacks (or g.Bytes via the *Bytes method variants).

Jump to

Keyboard shortcuts

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