### Install samber/lo Go Package Source: https://pkg.go.dev/github.com/samber/lo@v1.51.0/github.com/samber/lo This command installs the `samber/lo` Go package, specifically version v1. This package is versioned according to SemVer and has no external dependencies beyond the Go standard library. ```go go get github.com/samber/lo@v1 ``` -------------------------------- ### Makefile for Development Tasks Source: https://pkg.go.dev/github.com/samber/lo@v1.51.0/github.com/samber/lo This section outlines common development tasks managed by a Makefile, including installing dependencies and running tests. ```makefile # Install some dev dependencies make tools # Run tests make test # or make watch-test ``` -------------------------------- ### Go Numeric Slice Generation from Start Source: https://pkg.go.dev/github.com/samber/lo@v1.51.0/github.com/samber/lo RangeFrom creates a slice of numbers starting from a specified value and with a given length. It supports both integer and float types. The numbers increment by 1 from the start value. ```go func RangeFrom[T constraints.Integer | constraints.Float](start T, elementNum int) []T ``` -------------------------------- ### Docker Compose Development Environment Source: https://pkg.go.dev/github.com/samber/lo@v1.51.0/github.com/samber/lo This command executes the development environment setup using Docker Compose, providing a consistent environment for development tasks. ```bash docker-compose run --rm dev ``` -------------------------------- ### Get First Element: First (Go) Source: https://pkg.go.dev/github.com/samber/lo@v1.51.0/github.com/samber/lo Retrieves the first element from a collection and indicates its availability. Returns the zero value and false if the collection is empty. ```go first, ok := lo.First([]int{1, 2, 3}) // 1, true first, ok := lo.First([]int{}) // 0, false ``` -------------------------------- ### Get Random Sample: Sample (Go) Source: https://pkg.go.dev/github.com/samber/lo@v1.51.0/github.com/samber/lo Returns a random element from a collection. If the collection is empty, it returns the zero value of the element type. ```go lo.Sample([]string{"a", "b", "c"}) // a random string from []string{"a", "b", "c"} lo.Sample([]string{}) // "" ``` -------------------------------- ### Conditional Value Selection (Go) Source: https://pkg.go.dev/github.com/samber/lo@v1.51.0/github.com/samber/lo Returns a pointer to the `result` if the `condition` is true, otherwise returns nil. This is a starting point for chained conditional operations. ```Go func If[T any](condition bool, result T) *ifElse[T] ``` -------------------------------- ### Go: Drop elements from the beginning of a slice Source: https://pkg.go.dev/github.com/samber/lo@v1.51.0/github.com/samber/lo Drop removes n elements from the start of a slice or array. It requires the collection and the number of elements to drop. ```go func Drop[T any, Slice ~[]T](collection Slice, n int) Slice ``` -------------------------------- ### Go Numeric Slice Generation with Steps Source: https://pkg.go.dev/github.com/samber/lo@v1.51.0/github.com/samber/lo RangeWithSteps creates a slice of numbers progressing from a start value up to, but not including, an end value, with a specified step. It supports both integer and float types. If the step is zero, an empty slice is returned. ```go func RangeWithSteps[T constraints.Integer | constraints.Float](start, end, step T) []T ``` -------------------------------- ### First: Get First Element of a Go Slice Safely Source: https://pkg.go.dev/github.com/samber/lo@v1.51.0/github.com/samber/lo Retrieves the first element of a slice along with a boolean indicating its availability. If the slice is empty, it returns the zero value for the element type and `false`. ```go func First[T any](collection []T) (T, bool) { // ... implementation details ... } ``` -------------------------------- ### Generate Range of Numbers (Go) Source: https://pkg.go.dev/github.com/samber/lo@v1.51.0/github.com/samber/lo Creates a slice of integers or floats within a specified range. Supports generating sequences from zero up to a limit, from a start to an end, and with custom step values. Handles positive, negative, and zero ranges. ```go result := lo.Range(4) // [0, 1, 2, 3] result := lo.Range(-4) // [0, -1, -2, -3] result := lo.RangeFrom(1, 5) // [1, 2, 3, 4, 5] result := lo.RangeFrom[float64](1.0, 5) // [1.0, 2.0, 3.0, 4.0, 5.0] result := lo.RangeWithSteps(0, 20, 5) // [0, 5, 10, 15] result := lo.RangeWithSteps[float32](-1.0, -4.0, -1.0) // [-1.0, -2.0, -3.0] result := lo.RangeWithSteps(1, 4, -1) // [] result := lo.Range(0) // [] ``` -------------------------------- ### Slice: Get Slice Portion by Start and End Indices in Go Source: https://pkg.go.dev/github.com/samber/lo@v1.51.0/github.com/samber/lo Returns a copy of a portion of a slice specified by start and end indices. Similar to standard slicing `slice[start:end]`, but safely handles out-of-bounds indices without panicking. ```go in := []int{0, 1, 2, 3, 4} slice := lo.Slice(in, 0, 5) // []int{0, 1, 2, 3, 4} slice := lo.Slice(in, 2, 3) // []int{2} slice := lo.Slice(in, 2, 6) // []int{2, 3, 4} slice := lo.Slice(in, 4, 3) // []int{} ``` -------------------------------- ### Extract Substring (Go) Source: https://pkg.go.dev/github.com/samber/lo@v1.51.0/github.com/samber/lo Extracts a portion of a string based on start index and length. Negative start indices are supported, counting from the end of the string. `math.MaxUint` can be used as length to extract until the end. ```go package main import ( "fmt" "math" ) func main() { sub := lo.Substring("hello", 2, 3) fmt.Println(sub) // Output: "llo" subNegativeStart := lo.Substring("hello", -4, 3) fmt.Println(subNegativeStart) // Output: "ell" subToEnd := lo.Substring("hello", -2, math.MaxUint) fmt.Println(subToEnd) // Output: "lo" } ``` -------------------------------- ### Create Map from Key-Value Pairs (Go) Source: https://pkg.go.dev/github.com/samber/lo@v1.51.0/github.com/samber/lo Initializes a map from a slice of key-value pair entries. Each `Entry` struct represents a key-value pair to be inserted into the map. ```Go func FromPairs[K comparable, V any](entries []Entry[K, V]) map[K]V ``` -------------------------------- ### Keys Source: https://pkg.go.dev/github.com/samber/lo@v1.51.0/github.com/samber/lo Creates an array of the map keys. ```APIDOC ## func Keys[K comparable, V any](in ...map[K]V) []K ### Description Creates an array of the map keys. ### Method FUNC ### Endpoint Keys ### Parameters #### in (map[K]V) - **in** (map[K]V) - Required - The map(s) to extract keys from. ### Request Example N/A ### Response #### Success Response (200) - **[]K** ([]K) - An array containing the keys of the input map(s). #### Response Example ```json ["key1", "key2"] ``` ``` -------------------------------- ### Drop: Remove Elements from Start of Slice in Go Source: https://pkg.go.dev/github.com/samber/lo@v1.51.0/github.com/samber/lo Removes a specified number of elements from the beginning of a slice or array. ```go l := lo.Drop([]int{0, 1, 2, 3, 4, 5}, 2) // []int{2, 3, 4, 5} ``` -------------------------------- ### Keyify: Create a Set from Slice Elements in Go Source: https://pkg.go.dev/github.com/samber/lo@v1.51.0/github.com/samber/lo Creates a map where each unique element of the input slice is a key. This is commonly used to create a set-like structure. ```go set := lo.Keyify([]int{1, 1, 2, 3, 4}) // map[int]struct{}{1:{}, 2:{}, 3:{}, 4:{}} ``` -------------------------------- ### Get Last Element or Empty: LastOrEmpty (Go) Source: https://pkg.go.dev/github.com/samber/lo@v1.51.0/github.com/samber/lo Returns the last element of a collection or its zero value if the collection is empty. ```go last := lo.LastOrEmpty([]int{1, 2, 3}) // 3 last := lo.LastOrEmpty([]int{}) // 0 ``` -------------------------------- ### Implement Saga Pattern with Transaction Source: https://pkg.go.dev/github.com/samber/lo@v1.51.0/github.com/samber/lo Demonstrates how to implement the Saga pattern using the Transaction utility. It chains operations with corresponding rollback functions, allowing for managed execution and rollback in case of errors. Dependencies include standard Go libraries and the lo library. ```go transaction := NewTransaction(). Then( func(state int) (int, error) { fmt.Println("step 1") return state + 10, nil }, func(state int) int { fmt.Println("rollback 1") return state - 10 }, ). Then( func(state int) (int, error) { fmt.Println("step 2") return state + 15, nil }, func(state int) int { fmt.Println("rollback 2") return state - 15 }, ). Then( func(state int) (int, error) { fmt.Println("step 3") if true { return state, fmt.Errorf("error") } return state + 42, nil }, func(state int) int { fmt.Println("rollback 3") return state - 42 }, ) _, _ = transaction.Process(-5) ``` -------------------------------- ### Get First Element or Empty: FirstOrEmpty (Go) Source: https://pkg.go.dev/github.com/samber/lo@v1.51.0/github.com/samber/lo Returns the first element of a collection or its zero value if the collection is empty. ```go first := lo.FirstOrEmpty([]int{1, 2, 3}) // 1 first := lo.FirstOrEmpty([]int{}) // 0 ``` -------------------------------- ### Go Channel Buffering and Batching Functions Source: https://pkg.go.dev/github.com/samber/lo@v1.51.0/github.com/samber/lo Utilities for consuming data from channels. `Batch` and `BatchWithTimeout` read elements from a channel into slices. `Buffer` and `BufferWithTimeout` do similar but with additional timeout handling. `BufferWithContext` adds context cancellation. `ChannelDispatcher` distributes channel messages. ```Go func Batch[T any](ch <-chan T, size int) (collection []T, length int, readTime time.Duration, ok bool) func BatchWithTimeout[T any](ch <-chan T, size int, timeout time.Duration) (collection []T, length int, readTime time.Duration, ok bool) func Buffer[T any](ch <-chan T, size int) (collection []T, length int, readTime time.Duration, ok bool) func BufferWithContext[T any](ctx context.Context, ch <-chan T, size int) (collection []T, length int, readTime time.Duration, ok bool) func BufferWithTimeout[T any](ch <-chan T, size int, timeout time.Duration) (collection []T, length int, readTime time.Duration, ok bool) func ChannelDispatcher[T any](stream <-chan T, count int, channelBufferCap int, ...) []<-chan T ``` -------------------------------- ### Get Last Element or Fallback: LastOr (Go) Source: https://pkg.go.dev/github.com/samber/lo@v1.51.0/github.com/samber/lo Returns the last element of a collection or a specified fallback value if the collection is empty. ```go last := lo.LastOr([]int{1, 2, 3}, 245) // 3 last := lo.LastOr([]int{}, 31) // 31 ``` -------------------------------- ### Keyify Source: https://pkg.go.dev/github.com/samber/lo@v1.51.0/github.com/samber/lo Returns a map with each unique element of the slice as a key. ```APIDOC ## func Keyify[T comparable, Slice ~[]T](collection Slice) map[T]struct{} ### Description Returns a map with each unique element of the slice as a key. ### Method FUNC ### Endpoint Keyify ### Parameters #### collection (Slice) - **collection** (Slice) - Required - The slice to process. ### Request Example N/A ### Response #### Success Response (200) - **map[T]struct{}** (map[T]struct{}) - A map with unique elements from the slice as keys. #### Response Example ```json { "element1": {}, "element2": {} } ``` ``` -------------------------------- ### Create Map from Entries (Go) Source: https://pkg.go.dev/github.com/samber/lo@v1.51.0/github.com/samber/lo Constructs a map from a slice of `Entry` structs, where each entry contains a key-value pair. Useful for initializing maps from structured data. ```Go func FromEntries[K comparable, V any](entries []Entry[K, V]) map[K]V ``` -------------------------------- ### Get First Element or Fallback: FirstOr (Go) Source: https://pkg.go.dev/github.com/samber/lo@v1.51.0/github.com/samber/lo Returns the first element of a collection or a specified fallback value if the collection is empty. ```go first := lo.FirstOr([]int{1, 2, 3}, 245) // 1 first := lo.FirstOr([]int{}, 31) // 31 ``` -------------------------------- ### Go: Dispatch messages to channels using round-robin strategy Source: https://pkg.go.dev/github.com/samber/lo@v1.51.0/github.com/samber/lo DispatchingStrategyRoundRobin distributes messages sequentially in a rotating manner. If a channel is at capacity, the next channel in sequence is chosen. ```go func DispatchingStrategyRoundRobin[T any](msg T, index uint64, channels []<-chan T) int ``` -------------------------------- ### Empty - Go Source: https://pkg.go.dev/github.com/samber/lo@v1.51.0/github.com/samber/lo Returns the zero value for a given type. This is a convenient way to get the default value for any type without explicitly declaring it. ```go lo.Empty[int]() // 0 lo.Empty[string]() // "" lo.Empty[bool]() // false ``` -------------------------------- ### Create partially applied functions (2-5 args) in Go Source: https://pkg.go.dev/github.com/samber/lo@v1.51.0/github.com/samber/lo Functions like Partial2 to Partial5 allow creating partially applied functions where the first 2 to 5 arguments are pre-set. This is useful for simplifying function calls with many arguments. ```go add := func(x, y, z int) int { return x + y + z } f := lo.Partial2(add, 42) f(10, 5) // 57 f(42, -4) // 80 ``` -------------------------------- ### Fan-Out Channel Distribution (Go) Source: https://pkg.go.dev/github.com/samber/lo@v1.51.0/github.com/samber/lo Distributes elements from a single input channel to multiple output channels. `count` specifies the number of output channels, and `channelsBufferCap` sets their buffer size. Useful for parallel processing. ```Go func FanOut[T any](count int, channelsBufferCap int, upstream <-chan T) []<-chan T ``` -------------------------------- ### Import samber/lo Package in Go Source: https://pkg.go.dev/github.com/samber/lo@v1.51.0/github.com/samber/lo Demonstrates how to import the `samber/lo` package and its parallel and mutable sub-packages for use in Go projects. These imports allow access to various utility functions for collections and other data types. ```go import ( "github.com/samber/lo" lop "github.com/samber/lo/parallel" lom "github.com/samber/lo/mutable" ) ``` -------------------------------- ### Get Zero Value of Type (Go) Source: https://pkg.go.dev/github.com/samber/lo@v1.51.0/github.com/samber/lo Returns the zero value for a given generic type T. This is equivalent to calling the zero value for the type. ```Go func Empty[T any]() T ``` -------------------------------- ### Go Benchmark lo.Map Performance Source: https://pkg.go.dev/github.com/samber/lo@v1.51.0/github.com/samber/lo This section presents benchmark results comparing `lo.Map` against `lop.Map`, `go-funk`, and a standard Go `for` loop. It highlights `lo.Map`'s efficiency in terms of speed and memory allocation. ```go _ = lo.Map[int64](arr, func(x int64, i int) string { return strconv.FormatInt(x, 10) }) ``` -------------------------------- ### Get Last Element: Last (Go) Source: https://pkg.go.dev/github.com/samber/lo@v1.51.0/github.com/samber/lo Retrieves the last element from a collection and indicates its availability. Returns the zero value and false if the collection is empty. ```go last, ok := lo.Last([]int{1, 2, 3}) // 3 // true last, ok := lo.Last([]int{}) // 0 // false ``` -------------------------------- ### KebabCase Source: https://pkg.go.dev/github.com/samber/lo@v1.51.0/github.com/samber/lo Converts a string to kebab case. ```APIDOC ## func KebabCase(str string) string ### Description Converts string to kebab case. ### Method FUNC ### Endpoint KebabCase ### Parameters #### str (string) - **str** (string) - Required - The string to convert. ### Request Example N/A ### Response #### Success Response (200) - **string** (string) - The kebab-cased string. #### Response Example ```json "kebab-case-string" ``` ``` -------------------------------- ### ForEach Function Source: https://pkg.go.dev/github.com/samber/lo@v1.51.0/github.com/samber/lo%40v1.51.0/parallel Iterates over elements of a collection and invokes an iteratee function for each element in parallel. ```APIDOC ## ForEach ### Description ForEach iterates over elements of collection and invokes iteratee for each element. `iteratee` is called in parallel. ### Method func ### Endpoint N/A ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```go func ForEach[T any](collection []T, iteratee func(item T, index int)) ``` ### Response #### Success Response (200) None #### Response Example None ``` -------------------------------- ### Nil and Partial Function Application in Go Source: https://pkg.go.dev/github.com/samber/lo@v1.51.0/github.com/samber/lo Provides utilities for creating nil pointers of any type and for creating partially applied functions (closures) in Go. These functions enhance functional programming capabilities and memory management. ```go func Nil[T any]() *T func Partial[T1, T2, R any](f func(a T1, b T2) R, arg1 T1) func(T2) R func Partial1[T1, T2, R any](f func(T1, T2) R, arg1 T1) func(T2) R func Partial2[T1, T2, T3, R any](f func(T1, T2, T3) R, arg1 T1) func(T2, T3) R func Partial3[T1, T2, T3, T4, R any](f func(T1, T2, T3, T4) R, arg1 T1) func(T2, T3, T4) R func Partial4[T1, T2, T3, T4, T5, R any](f func(T1, T2, T3, T4, T5) R, arg1 T1) func(T2, T3, T4, T5) R func Partial5[T1, T2, T3, T4, T5, T6, R any](f func(T1, T2, T3, T4, T5, T6) R, arg1 T1) func(T2, T3, T4, T5, T6) R ``` -------------------------------- ### FirstOr: Get First Element or Fallback from Go Slice Source: https://pkg.go.dev/github.com/samber/lo@v1.51.0/github.com/samber/lo Returns the first element of a slice. If the slice is empty, it returns a provided fallback value instead. ```go func FirstOr[T any](collection []T, fallback T) T { // ... implementation details ... } ``` -------------------------------- ### Get Nth Element or Fallback: NthOr (Go) Source: https://pkg.go.dev/github.com/samber/lo@v1.51.0/github.com/samber/lo Returns the element at index 'nth' or a fallback value if the index is out of bounds. Negative indices count from the end. ```go nth := lo.NthOr([]int{10, 20, 30, 40, 50}, 2, -1) // 30 nth := lo.NthOr([]int{10, 20, 30, 40, 50}, -1, -1) // 50 nth := lo.NthOr([]int{10, 20, 30, 40, 50}, 5, -1) // -1 (fallback value) ``` -------------------------------- ### KeyBy: Create a map from a slice using a keying function in Go Source: https://pkg.go.dev/github.com/samber/lo@v1.51.0/github.com/samber/lo The KeyBy function transforms a slice into a map, where the map keys are generated by applying a pivot callback function to each element of the slice. If multiple elements produce the same key, the last one encountered will be the one stored in the map. It requires the 'github.com/samber/lo' package. ```go m := lo.KeyBy([]string{"a", "aa", "aaa"}, func(str string) int { return len(str) }) // map[int]string{1: "a", 2: "aa", 3: "aaa"} type Character struct { dir string code int } characters := []Character{ {dir: "left", code: 97}, {dir: "right", code: 100}, } result := lo.KeyBy(characters, func(char Character) string { return string(rune(char.code)) }) //map[a:{dir:left code:97} d:{dir:right code:100}] ``` -------------------------------- ### Go: Extract a sub-slice with overflow protection Source: https://pkg.go.dev/github.com/samber/lo@v1.51.0/github.com/samber/lo Subset returns a copy of a portion of a slice, starting at an offset and containing a specified number of elements. It avoids panics on overflow. ```Go func Subset[T any, Slice ~[]T](collection Slice, offset int, length uint) Slice ``` -------------------------------- ### Go Formatted Assertion with lo.Assertf Source: https://pkg.go.dev/github.com/samber/lo@v1.51.0/github.com/samber/lo Similar to `lo.Assert`, `lo.Assertf` checks a condition and panics if `false`. It allows for formatted error messages using `fmt.Printf`-style arguments. Use judiciously. ```go age := getUserAge() lo.Assertf(age >= 15, "user age must be >= 15, got %d", age) ``` -------------------------------- ### Retry Function Execution with Delay (Go) Source: https://pkg.go.dev/github.com/samber/lo@v1.51.0/github.com/samber/lo AttemptWithDelay invokes a function N times with a specified delay between each call, retrying until it returns successfully. It returns the number of iterations, total delay, and any error. Dependencies: time package. Input: Max iterations, delay duration, function returning error. Output: Iteration count, total delay, and error. ```go func AttemptWithDelay(maxIteration int, delay time.Duration, f func(index int, duration time.Duration) error) (int, time.Duration, error) ``` -------------------------------- ### Get Nil Pointer (Go) Source: https://pkg.go.dev/github.com/samber/lo@v1.51.0/github.com/samber/lo Returns a nil pointer of a specified generic type. This function is useful for creating zero-value pointers without explicit type declarations. ```go func Nil[T any]() *T ``` -------------------------------- ### Synchronization Primitive Source: https://pkg.go.dev/github.com/samber/lo@v1.51.0/github.com/samber/lo A utility for synchronizing access to resources using multiple `sync.Locker` instances. This is useful for complex locking scenarios. ```go func Synchronize(opt ...sync.Locker) *synchronize ``` -------------------------------- ### FirstOrEmpty: Get First Element or Zero Value from Go Slice Source: https://pkg.go.dev/github.com/samber/lo@v1.51.0/github.com/samber/lo Returns the first element of a slice. If the slice is empty, it returns the zero value of the element type. ```go func FirstOrEmpty[T any](collection []T) T { // ... implementation details ... } ``` -------------------------------- ### Get First Element or Fallback (Go) Source: https://pkg.go.dev/github.com/samber/lo@v1.51.0/github.com/samber/lo Returns the first element of a slice if it exists, otherwise returns a provided fallback value. Ensures a value is always returned. ```Go func FirstOr[T any](collection []T, fallback T) T ``` -------------------------------- ### Collection Partitioning and Filtering Source: https://pkg.go.dev/github.com/samber/lo@v1.51.0/github.com/samber/lo Functions for partitioning and filtering collections based on specified criteria. This includes partitioning by an iteratee function, picking elements by key, value, or predicate. ```go func PartitionBy[T any, K comparable, Slice ~[]T](collection Slice, iteratee func(item T) K) []Slice func PickBy[K comparable, V any, Map ~map[K]V](in Map, predicate func(key K, value V) bool) Map func PickByKeys[K comparable, V any, Map ~map[K]V](in Map, keys []K) Map func PickByValues[K comparable, V comparable, Map ~map[K]V](in Map, values []V) Map func Reject[T any, Slice ~[]T](collection Slice, predicate func(item T, index int) bool) Slice func RejectMap[T any, R any](collection []T, callback func(item T, index int) (R, bool)) []R ``` -------------------------------- ### Get Nth Element: Nth (Go) Source: https://pkg.go.dev/github.com/samber/lo@v1.51.0/github.com/samber/lo Retrieves the element at a specified index 'nth' from a collection. Negative indices count from the end. Returns an error if the index is out of bounds. ```go nth, err := lo.Nth([]int{0, 1, 2, 3}, 2) // 2 nth, err := lo.Nth([]int{0, 1, 2, 3}, -2) // 2 ``` -------------------------------- ### Go Integer Slice Generation (Range) Source: https://pkg.go.dev/github.com/samber/lo@v1.51.0/github.com/samber/lo Range creates a slice of integers with a specified length. The integers generated are positive and/or negative, starting from 0 and incrementing by 1. ```go func Range(elementNum int) []int ``` -------------------------------- ### Buffer Channel Data into Slice (Go) Source: https://pkg.go.dev/github.com/samber/lo@v1.51.0/github.com/samber/lo The Buffer function reads up to 'size' elements from a channel and returns them as a slice. It also returns the number of elements read, the time taken, and a boolean indicating if the channel is still open. This function is a replacement for the deprecated Batch function. Dependencies: None. Input: A channel and a size limit. Output: A slice of elements, count, read time, and channel status. ```go func Buffer[T any](ch <-chan T, size int) (collection []T, length int, readTime time.Duration, ok bool) ``` -------------------------------- ### Go Cross Join Functions Source: https://pkg.go.dev/github.com/samber/lo@v1.51.0/github.com/samber/lo Functions to perform cross joins on multiple slices, combining elements from each slice based on a projection function. They support joining from 2 up to 9 slices. The `project` function defines how elements from the joined slices are combined into the output type. ```Go func CrossJoinBy2[A, B, Out any](listA []A, listB []B, project func(a A, b B) Out) []Out func CrossJoinBy3[A, B, C, Out any](listA []A, listB []B, listC []C, project func(a A, b B, c C) Out) []Out func CrossJoinBy4[A, B, C, D, Out any](listA []A, listB []B, listC []C, listD []D, ...) []Out func CrossJoinBy5[A, B, C, D, E, Out any](listA []A, listB []B, listC []C, listD []D, listE []E, ...) []Out func CrossJoinBy6[A, B, C, D, E, F, Out any](listA []A, listB []B, listC []C, listD []D, listE []E, listF []F, ...) []Out func CrossJoinBy7[A, B, C, D, E, F, G, Out any](listA []A, listB []B, listC []C, listD []D, listE []E, listF []F, listG []G, ...) []Out func CrossJoinBy8[A, B, C, D, E, F, G, H, Out any](listA []A, listB []B, listC []C, listD []D, listE []E, listF []F, listG []G, ...) []Out func CrossJoinBy9[A, B, C, D, E, F, G, H, I, Out any](listA []A, listB []B, listC []C, listD []D, listE []E, listF []F, listG []G, ...) []Out ``` -------------------------------- ### Get First Element of Slice (Go) Source: https://pkg.go.dev/github.com/samber/lo@v1.51.0/github.com/samber/lo Retrieves the first element of a slice along with a boolean indicating if the slice was non-empty. Returns the zero value of T and false if the slice is empty. ```Go func First[T any](collection []T) (T, bool) ``` -------------------------------- ### Get Nth Element or Empty: NthOrEmpty (Go) Source: https://pkg.go.dev/github.com/samber/lo@v1.51.0/github.com/samber/lo Returns the element at index 'nth' or the zero value of the element type if the index is out of bounds. Negative indices count from the end. ```go nth := lo.NthOrEmpty([]int{10, 20, 30, 40, 50}, 2) // 30 nth := lo.NthOrEmpty([]int{10, 20, 30, 40, 50}, -1) // 50 nth := lo.NthOrEmpty([]int{10, 20, 30, 40, 50}, 5) // 0 (zero value for int) nth := lo.NthOrEmpty([]string{"apple", "banana", "cherry"}, 2) // "cherry" nth := lo.NthOrEmpty([]string{"apple", "banana", "cherry"}, 5) // "" (zero value for string) ``` -------------------------------- ### Repeat: Create a slice with N copies of a value in Go Source: https://pkg.go.dev/github.com/samber/lo@v1.51.0/github.com/samber/lo The Repeat function builds a new slice containing a specified number of copies of an initial value. Similar to `Fill`, if the value is a struct or pointer, it must implement a Clone method. It requires the 'github.com/samber/lo' package. ```go type foo struct { bar string } func (f foo) Clone() foo { return foo{f.bar} } slice := lo.Repeat(2, foo{"a"}) // []foo{foo{"a"}, foo{"a"}} ``` -------------------------------- ### RepeatBy: Build slice using a callback function in Go Source: https://pkg.go.dev/github.com/samber/lo@v1.51.0/github.com/samber/lo The RepeatBy function constructs a slice by repeatedly calling a provided callback function N times. The callback function receives the current index and its return value is added to the slice. It's useful for generating slices with dynamic values. It requires the 'github.com/samber/lo' package. ```go import "strconv" import "math" slice := lo.RepeatBy(0, func (i int) string { return strconv.FormatInt(int64(math.Pow(float64(i), 2)), 10) }) // []string{} slice := lo.RepeatBy(5, func(i int) string { return strconv.FormatInt(int64(math.Pow(float64(i), 2)), 10) }) // []string{"0", "1", "4", "9", "16"} ``` -------------------------------- ### Get Random Sample By Generator: SampleBy (Go) Source: https://pkg.go.dev/github.com/samber/lo@v1.51.0/github.com/samber/lo Returns a random element from a collection using a provided random integer generator function. Returns the zero value if the collection is empty. ```go import "math/rand" r := rand.New(rand.NewSource(42)) lo.SampleBy([]string{"a", "b", "c"}, r.Intn) // a random string from []string{"a", "b", "c"}, using a seeded random generator lo.SampleBy([]string{}, r.Intn) // "" ``` -------------------------------- ### Get Rune Count of String (Go) Source: https://pkg.go.dev/github.com/samber/lo@v1.51.0/github.com/samber/lo Returns the number of runes (Unicode code points) in a string. This is an alias for `utf8.RuneCountInString`. Unlike `len()`, it correctly handles multi-byte UTF-8 characters. ```go package main import "fmt" func main() { runeLen := lo.RuneLength("hellô") fmt.Println(runeLen) // Output: 5 byteLen := len("hellô") fmt.Println(byteLen) // Output: 6 (because 'ô' is a multi-byte character) } ``` -------------------------------- ### Create Channel Generator (Go) Source: https://pkg.go.dev/github.com/samber/lo@v1.51.0/github.com/samber/lo Creates a channel that generates values based on a provided generator function. The `generator` function uses a `yield` function to send values to the channel. `bufferSize` controls the channel's buffer capacity. ```Go func Generator[T any](bufferSize int, generator func(yield func(T))) <-chan T ``` -------------------------------- ### Go: Cartesian Product of 7 Lists (CrossJoin7) Source: https://pkg.go.dev/github.com/samber/lo@v1.51.0/github.com/samber/lo CrossJoin7 computes the Cartesian product for seven input lists, producing all possible element combinations. It returns an empty slice if any input list is empty. ```go func CrossJoin7[A, B, C, D, E, F, G any](listA []A, listB []B, listC []C, listD []D, listE []E, listF []F, listG []G) []Tuple7[A, B, C, D, E, F, G] { if len(listA) == 0 || len(listB) == 0 || len(listC) == 0 || len(listD) == 0 || len(listE) == 0 || len(listF) == 0 || len(listG) == 0 { return nil } result := make([]Tuple7[A, B, C, D, E, F, G], 0, len(listA)*len(listB)*len(listC)*len(listD)*len(listE)*len(listF)*len(listG)) for _, a := range listA { for _, b := range listB { for _, c := range listC { for _, d := range listD { for _, e := range listE { for _, f := range listF { for _, g := range listG { result = append(result, Tuple7[A, B, C, D, E, F, G]{A: a, B: b, C: c, D: d, E: e, F: f, G: g}) } } } } } } } return result } ``` -------------------------------- ### Go: Slice a collection with overflow protection Source: https://pkg.go.dev/github.com/samber/lo@v1.51.0/github.com/samber/lo Slice returns a copy of a portion of a slice from a start index up to (but not including) an end index. It is designed to prevent panics on overflow, unlike standard slicing. ```Go func Slice[T any, Slice ~[]T](collection Slice, start int, end int) Slice ``` -------------------------------- ### Go Error Handling with lo.Try Source: https://pkg.go.dev/github.com/samber/lo@v1.51.0/github.com/samber/lo The `lo.Try` function executes a given function and returns `true` if it completes without error or panic, and `false` otherwise. It's useful for simplifying error and panic handling in Go. ```go ok := lo.Try(func() error { panic("error") return nil }) // false ok := lo.Try(func() error { return nil }) // true ok := lo.Try(func() error { return fmt.Errorf("error") }) // false ``` -------------------------------- ### DropWhile: Remove Elements While Predicate is True (Start) in Go Source: https://pkg.go.dev/github.com/samber/lo@v1.51.0/github.com/samber/lo Removes elements from the beginning of a slice or array as long as a given predicate function returns true. Once the predicate returns false, no further elements are dropped. ```go l := lo.DropWhile([]string{"a", "aa", "aaa", "aa", "aa"}, func(val string) bool { return len(val) <= 2 }) // []string{"aaa", "aa", "aa"} ``` -------------------------------- ### Execute Function Asynchronously with Tuple Return (Go) Source: https://pkg.go.dev/github.com/samber/lo@v1.51.0/github.com/samber/lo Async2, Async3, Async4, Async5, and Async6 execute a function in a goroutine and return multiple results as a tuple through a channel. These functions are convenient for handling functions that return two to six values asynchronously. Dependencies: Tuple types (Tuple2, Tuple3, etc.). Input: A function returning multiple values. Output: A channel containing a tuple of the function's results. ```go func Async2[A, B any](f func() (A, B)) <-chan Tuple2[A, B] ``` ```go func Async3[A, B, C any](f func() (A, B, C)) <-chan Tuple3[A, B, C] ``` ```go func Async4[A, B, C, D any](f func() (A, B, C, D)) <-chan Tuple4[A, B, C, D] ``` ```go func Async5[A, B, C, D, E any](f func() (A, B, C, D, E)) <-chan Tuple5[A, B, C, D, E] ``` ```go func Async6[A, B, C, D, E, F any](f func() (A, B, C, D, E, F)) <-chan Tuple6[A, B, C, D, E, F] ``` -------------------------------- ### Get First Element or Zero Value (Go) Source: https://pkg.go.dev/github.com/samber/lo@v1.51.0/github.com/samber/lo Returns the first element of a slice if it exists, otherwise returns the zero value for the slice's element type. Similar to `FirstOr` with a zero fallback. ```Go func FirstOrEmpty[T any](collection []T) T ``` -------------------------------- ### Go Tuple9 Unpack Method Source: https://pkg.go.dev/github.com/samber/lo@v1.51.0/github.com/samber/lo The Unpack method for Tuple9 allows users to extract the nine individual values stored within the tuple, providing a direct way to access its components. ```go func (t Tuple9[A, B, C, D, E, F, G, H, I]) Unpack() (A, B, C, D, E, F, G, H, I) ``` -------------------------------- ### Get N Random Unique Samples: Samples (Go) Source: https://pkg.go.dev/github.com/samber/lo@v1.51.0/github.com/samber/lo Returns N unique random elements from a collection in a random order. If N is greater than the collection size, all elements are returned in random order. ```go lo.Samples([]string{"a", "b", "c"}, 3) // []string{"a", "b", "c"} in random order ``` -------------------------------- ### Error Handling and Try-Catch Mechanisms Source: https://pkg.go.dev/github.com/samber/lo@v1.51.0/github.com/samber/lo A comprehensive set of functions for robust error handling. This includes simple try-catch blocks, multi-value error returns, and fallback mechanisms for failed operations. ```go func Try(callback func() error) (ok bool) func Try0(callback func()) bool func Try1(callback func() error) bool func Try2[T any](callback func() (T, error)) bool func Try3[T, R any](callback func() (T, R, error)) bool func Try4[T, R, S any](callback func() (T, R, S, error)) bool func Try5[T, R, S, Q any](callback func() (T, R, S, Q, error)) bool func Try6[T, R, S, Q, U any](callback func() (T, R, S, Q, U, error)) bool func TryCatch(callback func() error, catch func()) func TryCatchWithErrorValue(callback func() error, catch func(any)) func TryOr[A any](callback func() (A, error), fallbackA A) (A, bool) func TryOr1[A any](callback func() (A, error), fallbackA A) (A, bool) func TryOr2[A, B any](callback func() (A, B, error), fallbackA A, fallbackB B) (A, B, bool) func TryOr3[A, B, C any](callback func() (A, B, C, error), fallbackA A, fallbackB B, fallbackC C) (A, B, C, bool) func TryOr4[A, B, C, D any](callback func() (A, B, C, D, error), fallbackA A, fallbackB B, fallbackC C, ...) (A, B, C, D, bool) func TryOr5[A, B, C, D, E any](callback func() (A, B, C, D, E, error), fallbackA A, fallbackB B, fallbackC C, ...) (A, B, C, D, E, bool) func TryOr6[A, B, C, D, E, F any](callback func() (A, B, C, D, E, F, error), fallbackA A, fallbackB B, ...) (A, B, C, D, E, F, bool) func TryWithErrorValue(callback func() error) (errorValue any, ok bool) ``` -------------------------------- ### Get Map Value or Default in Go Source: https://pkg.go.dev/github.com/samber/lo@v1.51.0/github.com/samber/lo Retrieves the value associated with a given key from a Go map. If the key is not found, it returns a specified fallback (default) value. This prevents panics when accessing potentially missing keys. ```go package main import ( "fmt" "github.com/samber/lo" ) func main() { value := lo.ValueOr(map[string]int{"foo": 1, "bar": 2}, "foo", 42) fmt.Println(value) // 1 value = lo.ValueOr(map[string]int{"foo": 1, "bar": 2}, "baz", 42) fmt.Println(value) // 42 } ``` -------------------------------- ### Go: Cartesian Product of 6 Lists (CrossJoin6) Source: https://pkg.go.dev/github.com/samber/lo@v1.51.0/github.com/samber/lo CrossJoin6 generates the Cartesian product for six input lists, yielding all unique combinations of elements. If any list is empty, an empty slice is returned. ```go func CrossJoin6[A, B, C, D, E, F any](listA []A, listB []B, listC []C, listD []D, listE []E, listF []F) []Tuple6[A, B, C, D, E, F] { if len(listA) == 0 || len(listB) == 0 || len(listC) == 0 || len(listD) == 0 || len(listE) == 0 || len(listF) == 0 { return nil } result := make([]Tuple6[A, B, C, D, E, F], 0, len(listA)*len(listB)*len(listC)*len(listD)*len(listE)*len(listF)) for _, a := range listA { for _, b := range listB { for _, c := range listC { for _, d := range listD { for _, e := range listE { for _, f := range listF { result = append(result, Tuple6[A, B, C, D, E, F]{A: a, B: b, C: c, D: d, E: e, F: f}) } } } } } } return result } ``` -------------------------------- ### Uniq: Get unique elements from a slice in Go Source: https://pkg.go.dev/github.com/samber/lo@v1.51.0/github.com/samber/lo Returns a new slice containing only the unique elements from the input slice, preserving the order of the first occurrence. Duplicate elements are removed. Useful for data cleaning and de-duplication. ```go uniqValues := lo.Uniq([]int{1, 2, 2, 1}) // []int{1, 2} ``` -------------------------------- ### Go Assertions Functions Source: https://pkg.go.dev/github.com/samber/lo@v1.51.0/github.com/samber/lo Provides functions for asserting conditions and handling potential errors. `Assert` checks a boolean condition and panics if false, optionally with a message. `Assertf` allows formatted error messages. These functions are useful for validating program state. ```Go func Assert(condition bool, message ...string) func Assertf(condition bool, format string, args ...any) ``` -------------------------------- ### Find Element and Index (Go) Source: https://pkg.go.dev/github.com/samber/lo@v1.51.0/github.com/samber/lo Searches a slice for the first element that satisfies the predicate, returning the element, its index, and a boolean indicating if it was found. Useful when the position of the found element is important. ```Go func FindIndexOf[T any](collection []T, predicate func(item T) bool) (T, int, bool) ``` -------------------------------- ### Type Conversion Utilities Source: https://pkg.go.dev/github.com/samber/lo@v1.51.0/github.com/samber/lo Utility functions for converting between data types, such as converting a slice of one type to a slice of `any`, or creating pointers to values. ```go func ToAnySlice[T any](collection []T) []any func ToPtr[T any](x T) *T func ToSlicePtr[T any](collection []T) []*T ``` -------------------------------- ### UniqBy: Get unique elements based on a criterion in Go Source: https://pkg.go.dev/github.com/samber/lo@v1.51.0/github.com/samber/lo Returns a slice with unique elements based on a criterion generated by an iteratee function. It ensures uniqueness based on the return value of the iteratee for each element, keeping the first occurrence. ```go uniqValues := lo.UniqBy([]int{0, 1, 2, 3, 4, 5}, func(i int) int { return i%3 }) // []int{0, 1, 2} ``` -------------------------------- ### Advanced Iteration and Reduction Source: https://pkg.go.dev/github.com/samber/lo@v1.51.0/github.com/samber/lo Functions for advanced iteration patterns, including reducing collections from both left and right, and generating collections based on an iteratee function. ```go func Reduce[T any, R any](collection []T, accumulator func(agg R, item T, index int) R, initial R) R func ReduceRight[T any, R any](collection []T, accumulator func(agg R, item T, index int) R, initial R) R func Times[T any](count int, iteratee func(index int) T) []T ``` -------------------------------- ### Use lo.Uniq for Unique String Slice in Go Source: https://pkg.go.dev/github.com/samber/lo@v1.51.0/github.com/samber/lo Example of using the `lo.Uniq` function from the `samber/lo` package to create a new slice containing only unique elements from an input string slice. This is a common operation for data cleaning and processing. ```go names := lo.Uniq([]string{"Samuel", "John", "Samuel"}) // names will be []string{"Samuel", "John"} ```