The root collection package includes a set of general-purpose helper functions. These standalone utilities complement the collection types and simplify common Go patterns.
| Function | Purpose |
|---|---|
| Value | Returns the given value unchanged (no-op). |
| ValueFunc | Calls a callback and returns its result (lazy evaluation). |
| Head | Safely returns the first element of a slice. |
| Last | Safely returns the last element of a slice. |
| WhenValue | Inline conditional for values. |
| WhenFunc | Inline conditional for callbacks (lazy). |
| Error Types | Specialized errors for collection operations. |
| Shared Types | Common type constraints and structures. |
func Value[T any](value T) TReturns the given value unchanged. Useful as a no-op callback or for consistent value resolution patterns.
v := collection.Value(42) // 42func ValueFunc[T any](callback func() T) TCalls the given callback and returns its result. Useful for deferred evaluation.
v := collection.ValueFunc(func() string {
return computeExpensiveDefault()
})func Head[T any](items []T) (T, bool)Returns the first element of a slice. Returns false if the slice is empty.
first, ok := collection.Head([]string{"alice", "bob"})
// first = "alice", ok = truefunc Last[T any](items []T) (T, bool)Returns the last element of a slice. Returns false if the slice is empty.
func WhenValue[T any](condition bool, value T, defaults ...T) TReturns value if condition is true, otherwise returns the first default or the zero value.
label := collection.WhenValue(isAdmin, "Admin Panel", "Dashboard")func WhenFunc[T any](condition bool, callback func() T, defaults ...func() T) TLike WhenValue but accepts callbacks for deferred evaluation. Only the required branch is executed.
Returned when a requested item is missing (e.g., FirstOrFail, Sole).
Returned by Sole when more than one item matches the predicate.
A type constraint for numeric types, used by aggregation functions like Sum and Avg.
A generic key-value pair used by Combine and MapCollection.
type Pair[K any, V any] struct {
Key K
Value V
}