gofn

package module
v1.17.1 Latest Latest
Warning

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

Go to latest
Published: Apr 15, 2026 License: MIT Imports: 16 Imported by: 9

README

Go Version GoDoc Build Status Coverage Status GoReport

gofn - Utility functions for Go

This is a collection of generics utility functions for Go 1.20+.

Functionalities

gofn consists of useful and convenient functions for most common needs when working on slices, maps, structs, transformation, conversion, and so on.

Check out my other libs:

Installation

go get github.com/tiendc/gofn

Function list

Slice

Slice searching

Slice filtering

Slice iteration

Slice uniqueness

Slice transformation

Slice algo

Slice conversion

Slice subset

Map

Struct

String

Number

Time

Math

Concurrency

Function

Execute Retry

Randomization

Error handling

Utility

Slice

Equal / EqualBy

Returns true if 2 slices have the same size and all elements of them equal in the current order.

Equal([]int{1, 2, 3}, []int{1, 2, 3}) // true
Equal([]int{1, 2, 3}, []int{3, 2, 1}) // false

// Use EqualBy for custom equal comparison
EqualBy([]string{"one", "TWO"}, []string{"ONE", "two"}, strings.EqualFold) // true
ContentEqual / ContentEqualBy

Returns true if 2 slices have the same size and contents equal regardless of the order of elements.

ContentEqual([]int{1, 2, 3}, []int{2, 1, 3})       // true
ContentEqual([]int{1, 2, 2, 3}, []int{2, 1, 3})    // false
ContentEqual([]int{1, 2, 2, 3}, []int{2, 1, 2, 3}) // true
ContentEqual([]int{1, 2, 2, 3}, []int{1, 1, 2, 3}) // false

// Use ContentEqualBy for custom key function
ContentEqualBy([]string{"one", "TWO"}, []string{"two", "ONE"}, strings.ToLower) // true
RemoveAt

Removes element at the specified index.

s := []int{1, 2, 3}
RemoveAt(&s, 1) // s == []int{1, 3}
FastRemoveAt

Removes element at the specified index by swapping it with the last element of the slice. This function is fast as it doesn't cause copying of slice content.

s := []int{1, 2, 3, 4}
FastRemoveAt(&s, 1) // s == []int{1, 4, 3} (2 and 4 are exchanged)
Sort / IsSorted

Convenient wrappers of the built-in sort.Slice.

Sort([]int{1, 3, 2})         // []int{1, 2, 3}
SortDesc([]int{1, 3, 2})     // []int{3, 2, 1}
IsSorted([]int{1, 3, 2})     // false
IsSortedDesc([]int{3, 2, 1}) // true
Remove

Removes a value from a slice.

s := []int{1, 2, 3}
Remove(&s, 1) // s == []int{2, 3}
FastRemove

Removes a value from a slice by swapping it with the last element of the slice.

s := []int{1, 2, 3, 4}
FastRemove(&s, 2) // s == []int{1, 4, 3} (2 and 4 are exchanged)
RemoveLastOf

Removes last occurrence of a value from a slice.

s := []int{1, 2, 1, 3}
RemoveLastOf(&s, 1) // s == []int{1, 2, 3}
FastRemoveLastOf

Removes last occurrence of a value from a slice by swapping it with the last element of the slice.

s := []int{1, 2, 1, 3, 4}
FastRemoveLastOf(&s, 1) // s == []int{1, 2, 4, 3} (1 and 4 are exchanged)
RemoveAll

Removes all occurrences of a value from a slice.

s := []int{1, 2, 1, 3, 1}
RemoveAll(&s, 1) // s == []int{2, 3}
Replace / ReplaceN / ReplaceAll

Replaces a value with another value.

// Replaces first occurrence of the value
Replace([]int{1, 2, 1, 3, 1}, 1, 11)     // []int{11, 2, 1, 3, 1}
// Replaces first n occurrences of the value (use -1 to replace all)
ReplaceN([]int{1, 2, 1, 3, 1}, 1, 11, 2) // []int{11, 2, 11, 3, 1}
// Replaces all occurrences of the value
ReplaceAll([]int{1, 2, 1, 3, 1}, 1, 11)  // []int{11, 2, 11, 3, 11}
Splice / SpliceEx

Removes a portion of the given slice and inserts elements of another slice into that position.

Usage: Splice(s []T, start int, deleteCount int, insertingElements ...T). If start < -len(s), 0 is used. If -len(s) <= start < 0, start + len(s) is used. If start >= len(s), no element will be deleted, but the new elements are still added to the end. If deleteCount <= 0, no elements will be removed.

s := Splice([]int{1, 2, 3}, 1, 1, 100)         // s == []int{1, 100, 3}
s := Splice([]int{1, 2, 3}, 1, 0, 100)         // s == []int{1, 100, 2, 3}
s := Splice([]int{1, 2, 3}, 1, 1, 100, 101)    // s == []int{1, 100, 101, 3}
s := Splice([]int{1, 2, 3}, 0, 2, 100, 101)    // s == []int{100, 101, 3}

// Use SpliceEx to get deleted items as the 2nd returning value
s, delItems := SpliceEx([]int{1, 2, 3}, 1, 1, 100)        // s == []int{1, 100, 3}, delItems == []int{2}
s, delItems := SpliceEx([]int{1, 2, 3}, 1, 0, 100)        // s == []int{1, 100, 2, 3}, delItems == []int{}
s, delItems := SpliceEx([]int{1, 2, 3}, 1, 1, 100, 101)   // s == []int{1, 100, 101, 3}, delItems == []int{2}
s, delItems := SpliceEx([]int{1, 2, 3}, 0, 2, 100, 101)   // s == []int{100, 101, 3}, delItems == []int{1, 2}
Concat

Concatenates two or more slices.

Concat([]int{1}, []int{2}, []int{2, 3}) // []int{1, 2, 2, 3}
Fill

Fills a slice with specified value.

s := make([]int, 5)
Fill(s, 1)  // s == []int{1, 1, 1, 1, 1}

s2 := s[2:4]
Fill(s2, 1) // s2 == []int{1, 1}, s == []int{0, 0, 1, 1, 0}
First / FirstOr

Returns the first element of slice.

First([]int{1, 2, 3})      // 1, true
First([]string{})          // "", false

// Return the default value if slice is empty
FirstOr([]int{1, 2, 3}, 4) // 1
FirstOr([]int{}, 11)       // 11
Last / LastOr

Returns the last element of slice.

Last([]int{1, 2, 3})       // 3, true
Last([]string{})           // "", false

// Return the default value if slice is empty
LastOr([]int{1, 2, 3}, 4)  // 3
LastOr([]int{}, 11)        // 11
SliceByRange

Generates a slice for the given range.

s := SliceByRange(0, 5, 1)         // []int{0, 1, 2, 3, 4}
s := SliceByRange(0.0, 5, 2)       // []float64{0, 2, 4}
s := SliceByRange(int32(5), 0, -2) // []int32{5, 3, 1}
Slice searching

Contain / ContainBy

Returns true if a slice contains a value.

Contain([]int{1, 2, 3}, 2) // true
Contain([]int{1, 2, 3}, 0) // false

// Use ContainBy for custom function
ContainBy([]string{"one", "TWO"}, func(elem string) bool {
    return strings.ToLower(elem) == "two"
}) // true
ContainAll

Returns true if a slice contains all given values.

ContainAll([]int{1, 2, 3, 4, 5}, 2, 4, 3) // true
ContainAll([]int{1, 2, 3, 4, 5}, 2, 7)    // false
ContainAny

Returns true if a slice contains any of the given values.

ContainAny([]int{1, 2, 3, 4, 5}, 2, 4, 7) // true
ContainAny([]int{1, 2, 3, 4, 5}, 7, 8, 9) // false
Find / FindEx

Finds a value in a slice.

v, found := Find([]string{"one", "TWO"}, func(elem string) bool {
    return strings.ToLower(elem) == "two"
}) // v == "TWO", found == true

// FindEx lets the given function decide which value to return
type Person struct {
    Name string
    Age  int
}
// Finds age of person having name "Tim"
ageOfTim, found := FindEx([]Person{{"John", 40}, {"Tim", 50}}, func(p Person) (int, bool) {
    return p.Age, p.Name == "Tim"
}) // ageOfTim == 50, found == true
FindLast / FindLastEx

Finds a value in a slice from the end.

v, found := FindLast([]string{"one", "TWO", "ONe"}, func(elem string) bool {
    return strings.ToLower(elem) == "one"
}) // v == "ONe", found == true

// FindLastEx lets the given function decide which value to return
type Person struct {
    Name string
    Age  int
}
// Finds age of the last person having name "tim"
ageOfTim, found := FindLastEx([]Person{{"John", 40}, {"Tim", 50}, {"TIM", 60}}, func(p Person) (int, bool) {
    return p.Age, strings.ToLower(p.Name) == "tim"
}) // ageOfTim == 60, found == true
IndexOf / IndexOfBy

Finds the index of a value in a slice, returns -1 if not found.

IndexOf([]int{1, 2, 3}, 4) // -1
IndexOf([]int{1, 2, 3}, 2) // 1

// Use IndexOfBy for custom function
IndexOfBy([]string{"one", "TWO"}, func(elem string) bool {
    return strings.ToLower(elem) == "two"
}) // 1
LastIndexOf / LastIndexOfBy

Finds the last index of an element in a slice, returns -1 if not found.

LastIndexOf([]int{1, 2, 3}, 4)    // -1
LastIndexOf([]int{1, 2, 1, 3}, 1) // 2
CountValue / CountValueBy

Counts the number of occurrences of a value in a slice.

CountValue([]int{1, 2, 3}, 4)    // 0
CountValue([]int{1, 2, 3, 2}, 2) // 2
Slice filtering

Filter

Filters a slice with condition.

Filter([]int{1, 2, 3, 4}, func (i int) bool {
    return i % 2 == 0
}) // []int{2, 4}

FilterLT([]int{1, 2, 3, 4}, 3)        // []int{1, 2}
FilterLTE([]int{1, 2, 3, 4}, 3)       // []int{1, 2, 3}
FilterGT([]int{1, 2, 3, 4}, 3)        // []int{4}
FilterGTE([]int{1, 2, 3, 4}, 3)       // []int{3, 4}
FilterRange([]int{1, 2, -2, 4}, 0, 3) // []int{1, 2}
FilterNE([]int{1, 2, 3, 4}, 3)        // []int{1, 2, 4}
FilterIN([]int{1, 2, 3, 4}, 3, 2, 7)  // []int{2, 3}
FilterNIN([]int{1, 2, 3, 4}, 3, 2, 7) // []int{1, 4}
FilterLIKE([]string{"*Abc*", "*abc*", "abc*", "*abc"}, "Abc")  // []string{"*Abc*"}
FilterILIKE([]string{"*Abc*", "*abc*", "abc*", "*abc"}, "Abc") // []string{"*Abc*", "*abc*", "abc*", "*abc"}
Slice iteration

ForEach / ForEachReverse

Iterates over slice content.

ForEach([]int{1, 2, 3}, func (i, v int) {
    fmt.Printf("%d ", v)
}) // prints 1 2 3

ForEachReverse([]int{1, 2, 3}, func (i, v int) {
    fmt.Printf("%d ", v)
}) // prints 3 2 1

// ForEachPtr can be faster if you iterate over a slice of big structs
ForEachPtr([]BigStruct{...}, func (i, v *BigStruct) { ... })
ForEachPtrReverse([]BigStruct{...}, func (i, v *BigStruct) { ... })
Iter / IterReverse

Iterates over one or multiple slices with ability to stop.

Iter(func (i, v int) bool {
    fmt.Printf("%d ", v)
    return i < 3
}, []int{1, 2, 3}, []int{4, 5}) // prints 1 2 3 4

IterReverse(func (i, v int) bool {
    fmt.Printf("%d ", v)
    return true
}, []int{1, 2, 3}, []int{4, 5}) // prints 5 4 3 2 1

// IterPtr can be faster if you iterate over a slice of big structs
IterPtr(func (i, v *BigStruct) bool { ... }, []BigStruct{...})
IterPtrReverse(func (i, v *BigStruct) bool { ... }, []BigStruct{...})
Slice uniqueness

IsUnique / IsUniqueBy

Returns true if a slice contains unique values.

IsUnique([]int{1, 2, 3}) // true
IsUnique([]int{1, 2, 1}) // false

// Use IsUniqueBy for custom function
IsUniqueBy([]string{"one", "ONE"}, strings.ToLower) // false
FindUniques / FindUniquesBy

Finds all unique elements in the given slice. The order of elements in the result is the same as they appear in the input.

FindUniques([]int{1, 2, 3, 2})  // []int{1, 3}
FindUniques([]int{1, 2, 2, 1})  // []int{}

// FindUniquesBy supports custom key function
FindUniquesBy([]string{"one", "ONE", "Two"}, func (s string) string {
    return strings.ToLower(s)
}) // []string{"Two"}
FindDuplicates / FindDuplicatesBy

Finds all elements which are duplicated in the given slice. The order of elements in the result is the same as they appear in the input.

FindDuplicates([]int{1, 2, 3, 2})  // []int{2}
FindDuplicates([]int{1, 2, 3})     // []int{}

// FindDuplicatesBy supports custom key function
FindDuplicatesBy([]string{"one", "ONE", "Two"}, func (s string) string {
    return strings.ToLower(s)
}) // []string{"one"}
ToSet / ToSetBy / ToSetByReverse

Calculates unique values of a slice.

ToSet([]int{1, 2, 3, 1, 2})        // []int{1, 2, 3}
ToSet([]string{"one", "2", "one"}) // []string{"one", "2"}

// Use ToSetBy for custom key function
ToSetBy([]string{"one", "TWO", "two", "One"}, strings.ToLower) // []string{"one", "TWO"}


// Use ToSetByReverse for iterating items from the end of the list
ToSetByReverse([]string{"one", "TWO", "two", "One"}, strings.ToLower) // []string{"One", "two"}
Slice transformation

MapSlice / MapSliceEx

Transforms a slice to a slice.

MapSlice([]string{"1", "2 ", " 3"}, strings.TrimSpace)   // []string{"1", "2", "3"}

// Use MapSliceEx to transform with error handling
MapSliceEx([]string{"1","2","3"}, gofn.ParseInt[int])    // []int{1, 2, 3}
MapSliceEx([]string{"1","x","3"}, gofn.ParseInt[int])    // strconv.ErrSyntax
MapSliceEx([]string{"1","200","3"}, gofn.ParseInt[int8]) // strconv.ErrRange
MapSliceToMap / MapSliceToMapEx

Transforms a slice to a map.

MapSliceToMap([]int{1, 2, 3}, func (i int) (int, string) {
    return i, fmt.Sprintf("%d", i)
}) // map[int]string{1: "1", 2: "2", 3: "3"}

// Use MapSliceToMapEx to transform with error handling
MapSliceToMapEx([]string{"1","300","3"}, func (s string) (string, int, bool) {
    v, e := gofn.ParseInt[int8](s)
    return s, v, e
}) // strconv.ErrRange
MapSliceToMapKeys

Transforms a slice to a map with using slice items as map keys.

MapSliceToMapKeys([]int{1, 2, 3, 2}, "x")     // map[int]string{1: "x", 2: "x", 3: "x"}
MapSliceToMapKeys([]int{1, 2, 1}, struct{}{}) // map[int]struct{}{1: struct{}{}, 2: struct{}{}}
Slice algo

Compact

Compacts a slice by removing zero elements. Not change the source slice.

s := Compact([]int{1, 0, 3}) // s == []int{1, 3}
Reverse / ReverseCopy

Reverses slice content.

Reverse([]int{1, 2, 3}) // []int{3, 2, 1}

s1 := []int{1, 2, 3}
s2 := ReverseCopy(s1)  // s1 == []int{1, 2, 3}, s2 == []int{3, 2, 1}
Drop

Returns a new slice with dropping values in the specified list. NOTE: this function is just a call to FilterNIN().

Drop([]int{1, 2, 3, 4}, 3, 1) // []int{2, 4}
Shuffle

Shuffle items of a slice. Not change the source slice.

s := Shuffle([]int{1, 2, 3}) // s is a new slice with random items of the input
Chunk / ChunkByPieces

Splits slice content into chunks.

Chunk([]int{1, 2, 3, 4, 5}, 2)         // [][]int{[]int{1, 2}, []int{3, 4}, []int{5}}
ChunkByPieces([]int{1, 2, 3, 4, 5}, 2) // [][]int{[]int{1, 2, 3}, []int{4, 5}}
Union / UnionBy

Finds all unique values from multiple slices.

Union([]int{1, 3, 2}, []int{1, 2, 2, 4}) // []int{1, 3, 2, 4}
Intersection / IntersectionBy

Finds all unique shared values from multiple slices.

Intersection([]int{1, 3, 2}, []int{1, 2, 2, 4}) // []int{1, 2}
Difference / DifferenceBy

Finds all different values from 2 slices.

left, right := Difference([]int{1, 3, 2}, []int{2, 2, 4}) // left == []int{1, 3}, right == []int{4}
Reduce / ReduceEx

Reduces a slice to a value.

Reduce([]int{1, 2, 3}, func (accumulator int, currentValue int) int {
    return accumulator + currentValue
}) // 6

ReduceEx([]int{1, 2, 3}, func (accumulator int, currentValue int, i index) int {
    return accumulator + currentValue
}, 10) // 16
ReduceReverse / ReduceReverseEx

Reduces a slice to a value with iterating from the end.

ReduceReverse([]int{1, 2, 3}, func (accumulator int, currentValue int) int {
    return accumulator + currentValue
}) // 6

ReduceReverseEx([]int{1, 2, 3}, func (accumulator int, currentValue int, i index) int {
    return accumulator + currentValue
}, 10) // 16
Partition / PartitionN

Splits a slice into multiple partitions.

// Splits a slice into 2 partitions
p0, p1 := Partition([]int{1, 2, 3, 4, 5}, func (v int, index int) bool {return v%2==0})) // p0 == []int{2, 4}, p1 == []int{1, 3, 5}

// Splits a slice into 3 partitions
p := PartitionN([]int{1, 2, 3, 4, 5}, 3, func (v int, index int) int {return v%3})) // p == [[3], [1, 4], [2, 5]]
Flatten / Flatten3

Flattens multi-dimension slice.

Flatten([]int{1, 2, 3}, []int{4, 5})                    // []int{1, 2, 3, 4, 5}
Flatten3([][]int{{1, 2}, {3, 4}, [][]int{{5, 6}, {7}}}) // []int{1, 2, 3, 4, 5, 6, 7}
Zip / Zip<N>

Combines values from multiple slices by each position (N is from 3 to 5).

Zip([]int{1, 2, 3}, []int{4, 5})                              // []*Tuple2{{1, 4), {2, 5}}
Zip3([]int{1, 2, 3}, []string{"4", "5"}, []float32{6.0, 7.0}) // []*Tuple3{{1, "4", 6.0), {2, "5", 7.0}}
Slice conversion

ToIfaceSlice

Converts a slice of any type to a slice of interfaces.

ToIfaceSlice([]int{1, 2, 3})         // []any{1, 2, 3}
ToIfaceSlice([]string{"foo", "bar"}) // []any{"foo", "bar"}
ToStringSlice

Converts a slice of string-approximate type to a slice of strings.

type XType string
ToStringSlice([]XType{XType("foo"), XType("bar")}) // []string{"foo", "bar"}
ToNumberSlice

Converts a slice of number type to a slice of specified number type.

ToNumberSlice[int]([]int8{1, 2, 3})    // []int{1, 2, 3}
ToNumberSlice[float32]([]int{1, 2, 3}) // []float32{1.0, 2.0, 3.0}

type XType int
ToNumberSlice[int]([]XType{XType(1), XType(2)}) // []int{1, 2}
ToSlice

Creates a slice for individual values.

ToSlice(1, 2, 3) // []int{1, 2, 3}
ToSliceSkippingNil / ToSliceSkippingZero

Creates a slice for individual values with skipping nil or zero ones.

v1 := 1
v2 := 2
ToSliceSkippingNil(nil, &v1, nil, &v2) // []*int{&v1, &v2}

ToSliceSkippingZero(1, 2, 0, 3)        // []int{1, 2, 3}
ToSliceSkippingZero("", "a", "")       // []string{"a"}
ToPtrSlice

Creates a slice of pointers point to the given elements.

s1 := []int{1, 2, 3}
s2 := ToPtrSlice(s1) // []*int{&s1[0], &s1[1], &s1[2]}
Slice subset

ContainSlice

Returns true if a slice contains another slice.

ContainSlice([]int{1, 2, 3, 4, 5}, []int{2, 3, 4}) // true
ContainSlice([]int{1, 2, 3, 4, 5}, []int{2, 4})    // false
IndexOfSlice

Finds the first occurrence of a sub-slice in a slice.

IndexOfSlice([]int{1, 2, 3, 4, 5}, []int{2, 3, 4}) // 1
IndexOfSlice([]int{1, 2, 3, 4, 5}, []int{2, 4})    // -1
LastIndexOfSlice

Finds the last occurrence of a sub-slice in a slice.

LastIndexOfSlice([]int{1, 2, 3, 1, 2, 3, 4}, []int{1, 2, 3}) // 3
LastIndexOfSlice([]int{1, 2, 3, 4, 5}, []int{2, 4})          // -1
SubSlice

Returns sub slice of a slice in range [start, end). end param is exclusive. This function doesn't raise error. Passing negative numbers for start and end to get items from the end of the slice.

SubSlice([]int{1, 2, 3}, 0, 2)   // []{1, 2}
SubSlice([]int{1, 2, 3}, -1, -2) // []{3}
SubSlice([]int{1, 2, 3}, -1, -3) // []{2, 3}
Map

MapEqual / MapEqualBy

Returns true if 2 maps equal.

MapEqual(map[int]string{1: "one", 2: "two"}, map[int]string{2: "two", 1: "one"}) // true
MapEqual(map[int]string{1: "one", 2: "two"}, map[int]string{1: "one", 2: "TWO"}) // false
MapContainKeys

Returns true if a map contains all given keys.

MapContainKeys(map[int]int{1: 11, 2: 22}, 1)    // true
MapContainKeys(map[int]int{1: 11, 2: 22}, 1, 2) // true
MapContainKeys(map[int]int{1: 11, 2: 22}, 1, 3) // false
MapContainValues

Returns true if a map contains all given values.

MapContainValues(map[int]int{1: 11, 2: 22}, 11)     // true
MapContainValues(map[int]int{1: 11, 2: 22}, 11, 22) // true
MapContainValues(map[int]int{1: 11, 2: 22}, 11, 33) // false
MapIter

Iterates over the entries of one or multiple maps.

MapIter(func(k int, v string) { ... }, map[int]string{1: "11", 2: "22"}, map[int]string{3: "33", 4: "44"})
MapKeys

Gets all keys of a map.

MapKeys(map[int]int{1: 11, 2: 22}) // []int{1, 2} (note: values may be in different order)
MapValues

Gets all values of a map.

MapValues(map[int]int{1: 11, 2: 22, 3: 22}) // []int{11, 22, 22} (note: values may be in different order)
MapEntries

Gets all entries (key, value) of a map.

MapEntries(map[int]int{1: 11, 2: 22}) // []*Tuple2[int,int]{{1,11}, {2,22}} (note: values may be in different order)
MapGet

Retrieves map value for a key, returns the default value if not exist.

MapGet(map[int]int{1: 11, 2: 22}, 1, 0) // 11 (found)
MapGet(map[int]int{1: 11, 2: 22}, 3, 0) // 0 (not found)
MapPop

Removes entry from a map and returns the current value if found.

MapPop(map[int]int{1: 11, 2: 22}, 1, 0) // 11 (found)
MapPop(map[int]int{1: 11, 2: 22}, 3, 0) // 0 (not found)
MapSetDefault

Sets default value for a key and returns the current value.

MapSetDefault(map[int]int{1: 11, 2: 22}, 1, 0) // 11 (no value added to the map)
MapSetDefault(map[int]int{1: 11, 2: 22}, 3, 0) // 0 (entry [3, 0] is added to the map)
MapUpdate / MapUpdateExistingOnly / MapUpdateNewOnly

Updates a map content with another map.

s := map[int]int{1: 11, 2: 22}
MapUpdate(s, map[int]int{1: 111, 3: 33})             // s == map[int]int{1: 111, 2: 22, 3: 33}
MapUpdateExistingOnly(s, map[int]int{2: 222, 3: 33}) // s == map[int]int{1: 11, 2: 222}
MapUpdateNewOnly(s, map[int]int{2: 222, 3: 33})      // s == map[int]int{1: 11, 2: 22, 3: 33}
MapCopy

Copies a map.

MapCopy(map[int]int{1: 11, 2: 22, 3: 33}) // map[int]int{1: 11, 2: 22, 3: 33}
MapPick

Copies map content for specified keys only.

MapPick(map[int]int{1: 11, 2: 22, 3: 33}, 2, 3, 2) // map[int]int{2: 22, 3: 33}
MapOmit

Omits keys from a map.

m := map[int]int{1: 11, 2: 22, 3: 33}
MapOmit(m, 2, 3, 4) // m == map[int]int{1: 11}
MapOmitCopy

Copies map content with omitting specified keys.

MapOmitCopy(map[int]int{1: 11, 2: 22, 3: 33}, 2, 3, 4) // map[int]int{1: 11}
MapReverse

Returns a new map with exchanging keys and values of the given map.

m, dupKeys := MapReverse(map[int]int{1: 11, 2: 22, 3: 33}) // m == map[int]int{11: 1, 22: 2, 33: 3} and dupKeys == []int{}
m, dupKeys := MapReverse(map[int]int{1: 11, 2: 11, 3: 33}) // m == map[int]int{11: <1 or 2>, 33: 3} and dupKeys == []int{1, 2}
Struct

StructToMap

Converts struct contents to a map. This function is a shortcut to rflutil.StructToMap.

ParseTag / ParseTagOf / ParseTagsOf

Parses struct tags. These functions are shortcuts to rflutil.ParseTag.

String

RuneLength

Alias of utf8.RuneCountInString.

len("café")        // 5
RuneLength("café") // 4
RandString / RandStringEx

Generates a random string.

RandString(10)                         // Generates a string of 10 characters from alphabets and digits
RandStringEx(10, []rune("0123456789")) // Generates a string of 10 characters from the specified ones
StringSplit / StringSplitN

Splits a string with handling quotes by ignoring any separator within the quotes.

StringSplit("ab cd \"12 34\"", " ", "\"")     // "[]string{"ab", "cd", "\"12 34\""}
StringSplit("ab cd {12 34}", " ", "{ }")      // "[]string{"ab", "cd", "{12 34}"}
StringSplitN("ab cd {12 34}", " ", "{ }", 2)  // "[]string{"ab", "cd {12 34}"}
StringJoin / StringJoinEx / StringJoinBy

Joins a slice of any element type.

s := StringJoin([]int{1,2,3}, ", ") // s == "1, 2, 3"

type Struct struct {
    I int
    S string
}
s := StringJoinBy([]Struct{{I:1, s:"a"}, {I:2, s:"b"}}, ", ", func (v Struct) string {
    return fmt.Sprintf("%d:%s", v.I, v.S)
}) // s == "1:a, 2:b"
StringLexJoin / StringLexJoinEx

Joins a slice of any element type in lexical manner.

StringLexJoin([]int{1,2,3}, ", ", " and ")              // return "1, 2 and 3"

// Use a custom format string
StringLexJoinEx([]int64{254, 255}, ", ", " or ", "%#x") // returns "0xfe or 0xff"
StringWrap / StringUnwrap

Wraps/Unwraps a string with the given tokens.

StringWrap("abc", "*")            // "*abc*"
StringWrapLR("abc", "[", "]")     // "[abc]"

StringUnwrap("*abc*", "*")        // "abc"
StringUnwrapLR("[abc]", "[", "]") // "abc"
StringToUpper1stLetter / StringToLower1stLetter

Capitalizes the first letter of a string.

StringToUpper1stLetter("abc")  // "Abc"
StringToLower1stLetter("Abc")  // "abc"
Number

ParseInt / ParseUint / ParseFloat

Parses a number using strconv.ParseInt then converts the value to a specific type.

ParseInt[int16]("111")            // int16(111)
ParseInt[int8]("128")             // strconv.ErrRange

// Return default value on failure
ParseIntDef("200", 10)            // int(200)
ParseIntDef("200", int8(10))      // int8(10)

// Parse integer with specific base
ParseIntEx[int8]("eeff1234", 16)  // strconv.ErrRange
ParseIntEx[int]("eeff1234", 16)   // int value for "eeff1234"

// Parse string containing commas
ParseInt[int]("1,234,567")        // strconv.ErrSyntax
ParseIntUngroup[int]("1,234,567") // int(1234567)
  • NOTE: There are also ParseUint for unsigned integers and ParseFloat for floating numbers.
FormatInt / FormatUint / FormatFloat

Formats a number value.

FormatInt(123)            // "123"

// Format number with specific format string (use fmt.Sprintf)
FormatIntEx(123, "%05d")  // "00123"

// Format number with decimal grouping
FormatIntGroup(1234567)   // "1,234,567"
  • NOTE: There are also FormatUint for unsigned integers and FormatFloat for floating numbers.
NumberFmtGroup

Groups digits of a number. Input number is of type string.

NumberFmtGroup("1234567", '.', ',')         // "1,234,567"
NumberFmtGroup("1234567", ',', '.')         // "1.234.567"
NumberFmtGroup("1234567.12345", '.', ',')   // "1,234,567.12345"
ToSafeInt<N> / ToSafeUint<N>

Safely casts an integer of any type to a specific type.

v, err := ToSafeInt8(-129)                     // err is ErrOverflow
v, err := ToSafeInt16(math.MaxUint16)          // err is ErrOverflow
v, err := ToSafeUint32(math.MaxUint64)         // err is ErrOverflow
v, err := ToSafeUint64(-1)                     // err is ErrOverflow

v, err := ToSafeInt8(127)                      // err == nil, v == int8(127)
v, err := ToSafeUint16(math.MaxInt16)          // err == nil, v == uint16(math.MaxInt16)
v, err := ToSafeInt32(math.MaxInt32)           // err == nil, v == int32(math.MaxInt32)
v, err := ToSafeUint64(uint64(math.MaxUint64)) // err == nil, v == uint64(math.MaxUint64)
Concurrency

ExecTasks / ExecTasksEx

Executes tasks concurrently with ease. This function provides a convenient way for one of the most popular use case in practical.

// In case you want to store the task results into a shared variable,
// make sure you use enough synchronization
var task1Result any
var task2Result []any

// Allow spending maximum 10s to finish all the tasks
ctx := context.WithTimeout(context.Background(), 10 * time.Second)

err := ExecTasks(ctx, 0 /* max concurrent tasks */,
    // Task 1st:
    func(ctx context.Context) (err error) {
        task1Result, err = getDataFromDB()
        return err
    },
    // Task 2nd:
    func(ctx context.Context) (err error) {
        for i:=0; i<10; i++ {
            if err := ctx.Err(); err != nil {
                return err
            }
            task2Result = append(task2Result, <some data>)
            return nil
        }
    },
)
if err != nil {
    // one or more tasks failed
}
ExecTaskFunc / ExecTaskFuncEx

Executes a task function on every target objects concurrently. This function is similar to ExecTasks(), but it takes only one function and a list of target objects.

var mu sync.Mutex
var evens []int
var odds []any

taskFunc := func(ctx context.Context, v int) error {
    mu.Lock()
    if v%2 == 0 {
        evens = append(evens, v)
    } else {
        odds = append(odds, v)
    }
    mu.Unlock()
    return nil
}

err := ExecTaskFunc(ctx, 0 /* max concurrent tasks */, taskFunc, 1, 2, 3, 4, 5)
if err != nil {
    // one or more tasks failed
}

// Result is: evens has [2, 4], odds has [1, 3, 5] (with undetermined order of items)
Function

Bind<N>Arg<M>Ret

Fully binds a function with returning a function which requires no argument.

func myCalc(a1 int, a2 string) error { ... }
myQuickCalc := Bind2Arg1Ret(myCalc, 100, "hello")
err := myQuickCalc()
Partial<N>Arg<M>Ret

Partially binds the first argument of a function.

func myCalc(a1 int, a2 string) error { ... }
myQuickCalc := Partial2Arg1Ret(myCalc, 100)
err := myQuickCalc("hello")
Randomization

NOTE: Should not use these functions for crypto purpose.


RandChoice

Picks up an item randomly from a list of items.

val, valid := RandChoice(1, 2, 3) // valid == true and `val` is one of the input items
val, valid := RandChoice[int]()   // valid == false and `val` is int(0)
RandChoiceMaker

Provides a method to pick up items randomly from a list of items without duplication of choice.

choiceMaker := NewRandChoiceMaker([]int{1, 2, 3})
for choiceMaker.HasNext() {
    randItem, _ := choiceMaker.Next()
}
// OR
for {
    randItem, valid := choiceMaker.Next()
    if !valid {
        break
    }
}
RandToken / RandTokenAsHex

Generates random tokens using crypto/rand package. The output can be used for crypto purpose. These functions should not be called concurrently.

RandToken(numBytes)      // returns []byte of size numBytes
RandTokenAsHex(numBytes) // returns a string of size numBytes*2
Execute Retry

ExecRetry / ExecRetryN

Executes a function multiple times until it succeeds or reaches the designated limits. Delays are paused between attempts. Supports up to 5 generic return values.

// Delay 1 second between retries, maximum 3 retries (4 executions total)
err := ExecRetry(func() error {
    return doSomething()
}, 3, time.Second)

// Advanced usage: Exponential backoff with jitter
err = ExecRetry(func() error {
    return doSomething()
}, 3, 100*time.Millisecond, ExecRetryDelayExpoBackoff(10*time.Millisecond))

// Advanced usage: Custom retryable check
err = ExecRetry(func() error {
return doSomething()
}, 3, 100*time.Millisecond, ExecRetryIfErrorIs(<ErrConflict>, <ErrAlreadyExist>))

// Returning values alongside errors
v, err := ExecRetry2(func() (int, error) {
    return getID()
}, 3, time.Second)
ExecRetryCtx / ExecRetryCtxN

Context-aware variadic retry execution. Operates exactly like standard variants but safely yields on context.Done() to cancel in-flight waiting intervals instantly.

ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()

// Retries will safely abort if `ctx` is canceled/expires
err := ExecRetryCtx(ctx, func() error {
    return doSomething()
}, 3, time.Second)

v1, v2, err := ExecRetryCtx3(ctx, func() (int, string, error) {
    return getValues()
}, 3, time.Second)
Error handling

ErrWrap / ErrWrapL

Convenient functions to wrap a single error with a single message.

// shortcut call of fmt.Errorf("%w: %s")
e := ErrWrap(err, "failed to do something")

// shortcut call of fmt.Errorf("%s: %w")
e := ErrWrapL("failed to do something", err)
ErrUnWrap

Unwraps an error into a slice of errors. This function can unwrap an error created by errors.Join() and fmt.Errorf(<one or multiple errors passed here>).

e1 := errors.New("e1")
e2 := errors.New("e2")
e3 := errors.Join(e1, e2)
e4 := fmt.Errorf("%w, %w", e1, e2)

errs := ErrUnwrap(e1) // errs == []error{e1}
errs := ErrUnwrap(e3) // errs == []error{e1,e2}
errs := ErrUnwrap(e4) // errs == []error{e1,e2}
ErrUnwrapToRoot

Unwraps an error until the deepest one.

e1 := errors.New("e1")
e2 := fmt.Errorf("e2: %w", e1)
e3 := fmt.Errorf("e3: %w", e2)

e := ErrUnwrapToRoot(e3) // e == e1
e := ErrUnwrapToRoot(e2) // e == e1
Time

MinTime / MaxTime / MinMaxTime

Finds minimum/maximum time value in a slice.

t0 := time.Time{}
t1 := time.Date(2000, time.December, 1, 0, 0, 0, 0, time.UTC)
t2 := time.Date(2001, time.December, 1, 0, 0, 0, 0, time.UTC)
MinTime(t0, t1, t2)     // t0
MinTime(t1, t2)         // t1
MaxTime(t0, t1, t2)     // t2
MinMaxTime(t0, t1, t2)  // t0, t2
ExecDuration / ExecDurationN

Measures time executing a function.

duration := ExecDuration(func() { // do something })
// The given function returns a value
outVal, duration := ExecDuration1(func() string { return "hello" })              // outVal == "hello"
// The given function returns 2 values
outVal1, err, duration := ExecDuration2(func() (int, error) { return 123, nil }) // outVal1 == 123, err == nil
ExecDelay

Executes a function after a time duration. This function is just an alias of time.AfterFunc.

timer := ExecDelay(3*time.Second, func() {
    // do something after waiting 3 seconds
})
Math

All

Returns true if all given values are evaluated true.

All(1, "1", 0.5) // true
All(1, "1", 0.0) // false
All(1, "", -1)   // false
All()            // true
Any

Returns true if any of the given values is evaluated true.

Any(1, "", 0.5)  // true
Any(1, "1", 0.0) // true
Any(0, "", 0.0)  // false
Any()            // false
Abs

Calculates absolute value of an integer.

Abs(-123)          // int64(123)
Abs(123)           // int64(123)
Abs(math.MinInt64) // math.MinInt64 (special case)
Clamp

Clamps a value within a range (lower and upper bounds are inclusive).

Clamp(3, 10, 20)  // 10
Clamp(30, 10, 20) // 20
Clamp(15, 10, 20) // 15
Min / Max / MinMax

Finds minimum/maximum value in a slice.

Min(1, 2, 3, -1)             // -1
MinIn([]int{1, 2, 3, -1})    // -1
MinInBy([]string{"a", "B"}, func(a, b int) bool {
    return strings.ToLower(a) < strings.ToLower(b)
}) // "a"

Max(1, 2, 3, -1)             // 3
MaxIn([]int{1, 2, 3, -1})    // 3
MaxInBy([]string{"a", "B"}, func(a, b int) bool {
    return strings.ToLower(a) < strings.ToLower(b)
}) // "B"

MinMax(1, 2, 3, -1)          // -1, 3
Sum / SumAs

Calculates sum value of slice elements.

Sum([]int{1, 2, 3})            // 6
SumAs[int]([]int8{50, 60, 70}) // 180 (Sum() will fail as the result overflows int8)
Product / ProductAs

Calculates product value of slice elements.

Product([]int{1, 2, 3})         // 6
ProductAs[int]([]int8{5, 6, 7}) // 210 (Product() will fail as the result overflows int8)
Utility

FirstNonEmpty

Returns the first non-empty value in the given arguments if found, otherwise returns the zero value. This function uses reflection. You can connsider using Coalesce for generic types.

Values considered "non-empty" are:

  • not empty values (0, empty string, false, nil, ...)
  • not empty containers (slice, array, map, channel)
  • not pointers that point to zero/empty values
FirstNonEmpty(0, -1, 2, 3)                          // -1
FirstNonEmpty("", " ", "b")                         // " "
FirstNonEmpty([]int{}, nil, []int{1}, []int{2, 3})  // []int{1}
FirstNonEmpty([]int{}, nil, &[]int{}, []int{2, 3})  // []int{2, 3}
FirstNonEmpty[any](nil, 0, 0.0, "", struct{}{})     // nil (the first zero value)
Coalesce

Returns the first non-zero argument. Input type must be comparable.

Coalesce(0, -1, 2)         // -1
Coalesce("", " ", "s")     // " "
Coalesce[*int](ptr1, ptr2) // the first non-nil pointer
If

A convenient function works like C ternary operator.

WARNING: This function may cause the program to crash on misuses due to both passing expressions are evaluated regardless of the condition. For example: firstItem := If(len(slice) > 0, slice[0], defaultVal) will crash if slice is empty as the expression slice[0] is always evaluated. Use it at your own risk.

val := If(x > 100, val1, val2) // If x > 100, val == val1, otherwise val == val2
Must<N>

Must<N> ( N is from 1 to 6) functions accept a number of arguments with the last one is of error type. Must<N> functions return the first N-1 arguments if the error is nil, otherwise they panic.

func CalculateAmount() (int, error) {}
amount := Must(CalculateAmount()) // panic on error, otherwise returns the amount

func CalculateData() (int, string, float64, error) {}
v1, v2, v3 := Must4(CalculateData()) // panic on error, otherwise returns the 3 first values
ToPtr

Returns a pointer to the input argument.

func aFunc(ptr *int) {}

// Use ToPtr to pass a value inline
aFunc(ToPtr(10))
PtrValueOrEmpty

Returns the value pointed by a pointer or an empty value if it's nil.

PtrValueOrEmpty(ToPtr(3))   // 3
PtrValueOrEmpty[int](nil)   // 0
PtrValueOrEmpty[*int](nil)  // nil
Head

Takes the first argument.

Head(1, "2", 1.0, 3)   // 1
Tail

Takes the last argument.

Tail[string](true, "2", 1.0, "3") // "3"

Benchmarks

Equal vs ContentEqual vs reflect.DeepEqual

Benchmark_Slice_Equal/StructSlice/Equal
Benchmark_Slice_Equal/StructSlice/Equal-8           510845715           2.047 ns/op
Benchmark_Slice_Equal/StructSlice/ContentEqual
Benchmark_Slice_Equal/StructSlice/ContentEqual-8    583167950           2.061 ns/op
Benchmark_Slice_Equal/StructSlice/DeepEqual
Benchmark_Slice_Equal/StructSlice/DeepEqual-8       15403771            79.19 ns/op

Benchmark_Slice_Equal/IntSlice/Equal
Benchmark_Slice_Equal/IntSlice/Equal-8              589706185           2.087 ns/op
Benchmark_Slice_Equal/IntSlice/ContentEqual
Benchmark_Slice_Equal/IntSlice/ContentEqual-8       523120755           2.194 ns/op
Benchmark_Slice_Equal/IntSlice/DeepEqual
Benchmark_Slice_Equal/IntSlice/DeepEqual-8          15243183            77.93 ns/op

Contributing

  • You are welcome to make pull requests for new functions and bug fixes.

License

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	ErrEmpty           = errors.New("container is empty")
	ErrIndexOutOfRange = errors.New("index out of range")
	ErrOverflow        = errors.New("overflow")
	ErrPanic           = errors.New("panic occurred")
)
View Source
var (
	StrLowerAlpha   = []rune("abcdefghijklmnopqrstuvwxyz")
	StrUpperAlpha   = []rune("ABCDEFGHIJKLMNOPQRSTUVWXYZ")
	StrAlpha        = Concat(StrLowerAlpha, StrUpperAlpha)
	StrDigits       = []rune("0123456789")
	StrAlphaNumeric = Concat(StrAlpha, StrDigits)
	StrSpecialChars = []rune("~!@#$%^&*()-_+`'\";:,.<>/?{[}]\\|")
	StrAllChars     = Concat(StrAlpha, StrDigits, StrSpecialChars)
	StrDefaultChars = StrAlphaNumeric
)
View Source
var (
	StructToMap = rflutil.StructToMap
	ParseTag    = rflutil.ParseTag
	ParseTagOf  = rflutil.ParseTagOf
	ParseTagsOf = rflutil.ParseTagsOf
)
View Source
var ExecDelay = time.AfterFunc

ExecDelay is an alias of time.AfterFunc

View Source
var MultilineString = LinesTrimLeftSpace

Deprecated

RuneLength alias of utf8.RuneCountInString

Functions

func Abs

func Abs(n int64) int64

Abs calculates absolute value of an integer. Ref: http://cavaliercoder.com/blog/optimized-abs-for-int64-in-go.html. Note: if inputs MinInt64, the result is negative.

func All

func All[T comparable](s ...T) bool

All returns true if all given values are evaluated as `true`

func Any

func Any[T comparable](s ...T) bool

Any returns true if at least one of given values is evaluated as `true`

func Bind1Arg0Ret added in v1.5.0

func Bind1Arg0Ret[A1 any](fn func(A1), a1 A1) func()

func Bind1Arg1Ret added in v1.5.0

func Bind1Arg1Ret[A1 any, R1 any](fn func(A1) R1, a1 A1) func() R1

func Bind1Arg2Ret added in v1.5.0

func Bind1Arg2Ret[A1 any, R1 any, R2 any](fn func(A1) (R1, R2), a1 A1) func() (R1, R2)

func Bind1Arg3Ret added in v1.5.0

func Bind1Arg3Ret[A1 any, R1 any, R2 any, R3 any](fn func(A1) (R1, R2, R3), a1 A1) func() (R1, R2, R3)

func Bind2Arg0Ret added in v1.5.0

func Bind2Arg0Ret[A1 any, A2 any](fn func(A1, A2), a1 A1, a2 A2) func()

func Bind2Arg1Ret added in v1.5.0

func Bind2Arg1Ret[A1 any, A2 any, R1 any](fn func(A1, A2) R1, a1 A1, a2 A2) func() R1

func Bind2Arg2Ret added in v1.5.0

func Bind2Arg2Ret[A1 any, A2 any, R1 any, R2 any](fn func(A1, A2) (R1, R2), a1 A1, a2 A2) func() (R1, R2)

func Bind2Arg3Ret added in v1.5.0

func Bind2Arg3Ret[A1 any, A2 any, R1 any, R2 any, R3 any](fn func(A1, A2) (R1, R2, R3), a1 A1, a2 A2) func() (R1, R2, R3)

nolint: lll

func Bind3Arg0Ret added in v1.5.0

func Bind3Arg0Ret[A1 any, A2 any, A3 any](fn func(A1, A2, A3), a1 A1, a2 A2, a3 A3) func()

func Bind3Arg1Ret added in v1.5.0

func Bind3Arg1Ret[A1 any, A2 any, A3 any, R1 any](fn func(A1, A2, A3) R1, a1 A1, a2 A2, a3 A3) func() R1

func Bind3Arg2Ret added in v1.5.0

func Bind3Arg2Ret[A1 any, A2 any, A3 any, R1 any, R2 any](fn func(A1, A2, A3) (R1, R2), a1 A1, a2 A2, a3 A3) func() (R1, R2)

nolint: lll

func Bind3Arg3Ret added in v1.5.0

func Bind3Arg3Ret[A1 any, A2 any, A3 any, R1 any, R2 any, R3 any](fn func(A1, A2, A3) (R1, R2, R3), a1 A1, a2 A2, a3 A3) func() (R1, R2, R3)

nolint: lll

func Bind4Arg0Ret added in v1.5.0

func Bind4Arg0Ret[A1 any, A2 any, A3 any, A4 any](fn func(A1, A2, A3, A4), a1 A1, a2 A2, a3 A3, a4 A4) func()

func Bind4Arg1Ret added in v1.5.0

func Bind4Arg1Ret[A1 any, A2 any, A3 any, A4 any, R1 any](fn func(A1, A2, A3, A4) R1, a1 A1, a2 A2, a3 A3, a4 A4) func() R1

nolint: lll

func Bind4Arg2Ret added in v1.5.0

func Bind4Arg2Ret[A1 any, A2 any, A3 any, A4 any, R1 any, R2 any](fn func(A1, A2, A3, A4) (R1, R2), a1 A1, a2 A2, a3 A3, a4 A4) func() (R1, R2)

nolint: lll

func Bind4Arg3Ret added in v1.5.0

func Bind4Arg3Ret[A1 any, A2 any, A3 any, A4 any, R1 any, R2 any, R3 any](fn func(A1, A2, A3, A4) (R1, R2, R3), a1 A1, a2 A2, a3 A3, a4 A4) func() (R1, R2, R3)

nolint: lll

func Bind5Arg0Ret added in v1.5.0

func Bind5Arg0Ret[A1 any, A2 any, A3 any, A4 any, A5 any](fn func(A1, A2, A3, A4, A5), a1 A1, a2 A2, a3 A3, a4 A4, a5 A5) func()

nolint: lll

func Bind5Arg1Ret added in v1.5.0

func Bind5Arg1Ret[A1 any, A2 any, A3 any, A4 any, A5 any, R1 any](fn func(A1, A2, A3, A4, A5) R1, a1 A1, a2 A2, a3 A3, a4 A4, a5 A5) func() R1

nolint: lll

func Bind5Arg2Ret added in v1.5.0

func Bind5Arg2Ret[A1 any, A2 any, A3 any, A4 any, A5 any, R1 any, R2 any](fn func(A1, A2, A3, A4, A5) (R1, R2), a1 A1, a2 A2, a3 A3, a4 A4, a5 A5) func() (R1, R2)

nolint: lll

func Bind5Arg3Ret added in v1.5.0

func Bind5Arg3Ret[A1 any, A2 any, A3 any, A4 any, A5 any, R1 any, R2 any, R3 any](fn func(A1, A2, A3, A4, A5) (R1, R2, R3), a1 A1, a2 A2, a3 A3, a4 A4, a5 A5) func() (R1, R2, R3)

nolint: lll

func Chunk

func Chunk[T any, S ~[]T](s S, chunkSize int) []S

Chunk splits slice content into chunks by chunk size

func ChunkByPieces

func ChunkByPieces[T any, S ~[]T](s S, chunkCount int) []S

ChunkByPieces splits slice content into chunks by number of pieces

func Clamp added in v1.10.0

func Clamp[T NumberExt | StringExt](value, min, max T) T

Clamp clamps number within the inclusive lower and upper bounds.

func Coalesce added in v1.11.0

func Coalesce[T comparable](args ...T) (result T)

Coalesce returns the first non-zero value if found, otherwise returns zero.

func Compact

func Compact[T comparable, S ~[]T](s S) S

Compact excludes all zero items in a slice

func Concat

func Concat[T any, S ~[]T](slices ...S) S

Concat concatenates slices

func Contain

func Contain[T comparable, S ~[]T](a S, t T) bool

Contain tests if a slice contains an item

func ContainAll

func ContainAll[T comparable, S ~[]T](a S, b ...T) bool

ContainAll tests if a slice contains all given values

func ContainAny

func ContainAny[T comparable, S ~[]T](a S, b ...T) bool

ContainAny tests if a slice contains any given value

func ContainBy added in v1.10.0

func ContainBy[T any, S ~[]T](a S, pred func(t T) bool) bool

ContainBy tests if a slice contains an item by predicate

func ContainByPtr added in v1.10.0

func ContainByPtr[T any, S ~[]T](a S, pred func(t *T) bool) bool

ContainByPtr tests if a slice contains an item by predicate

func ContainSlice

func ContainSlice[T comparable, S ~[]T](a, b S) bool

ContainSlice tests if a slice contains a slice

func ContentEqual

func ContentEqual[T comparable, S ~[]T](a, b S) bool

ContentEqual compares 2 slices without caring about order. NOTE: if you want to compare content of slices of pointers, use ContentEqualPtr.

func ContentEqualBy added in v1.10.0

func ContentEqualBy[T any, K comparable, S ~[]T](a, b S, keyFunc func(t T) K) bool

ContentEqualBy compares 2 slices without preserving order

func ContentEqualPtr

func ContentEqualPtr[T comparable, S ~[]*T](a, b S) bool

ContentEqualPtr compares 2 slices of pointers without caring about order

func CountValue

func CountValue[T comparable, S ~[]T](a S, val T) int

CountValue counts number of occurrences of an item in the slice

func CountValueBy added in v1.10.0

func CountValueBy[T any, S ~[]T](a S, pred func(t T) bool) int

CountValueBy counts number of occurrences of an item in the slice

func Difference

func Difference[T comparable, S ~[]T](a, b S) (S, S)

Difference calculates the differences between two slices. The first result list contains all the values exist in the left list, but the right. The second result list contains all the values exist in the right list, but the left. NOTE: this function does not return unique values.

func DifferenceBy added in v1.10.0

func DifferenceBy[T any, K comparable, S ~[]T](a, b S, keyFunc func(t T) K) (S, S)

DifferenceBy calculates the differences between two slices using special key function. NOTE: this function does not return unique values.

func Drop added in v1.9.0

func Drop[T comparable, S ~[]T](a S, values ...T) S

Drop returns a copied slice with dropping items in the list

func Equal

func Equal[T comparable, S ~[]T](a, b S) bool

Equal compares 2 slices with preserving order

func EqualBy added in v1.10.0

func EqualBy[T any, S ~[]T](a, b S, equalCmp func(a, b T) bool) bool

EqualBy compares 2 slices with preserving order

func EqualByPtr added in v1.10.0

func EqualByPtr[T any, S ~[]T](a, b S, equalCmp func(a, b *T) bool) bool

EqualByPtr compares 2 slices with preserving order

func ErrUnwrap added in v1.14.0

func ErrUnwrap(err error) []error

ErrUnwrap unwraps an error to get a slice. This function can unwrap error created by errors.Join() and fmt.Errorf(<multiple errors passed>). In case there's only single item wrapped in the input, the slice has only 1 item.

func ErrUnwrapToRoot added in v1.14.0

func ErrUnwrapToRoot(err error) error

ErrUnwrapToRoot unwraps an error until the deepest one

func ErrWrap added in v1.14.0

func ErrWrap(err error, msg string) error

ErrWrap wraps an error with a message placed in the right

func ErrWrapL added in v1.14.0

func ErrWrapL(msg string, err error) error

ErrWrapL wraps an error with a message placed in the left

func ExecDuration added in v1.10.0

func ExecDuration(fn func()) time.Duration

ExecDuration measures time duration of running a function

func ExecDuration1 added in v1.10.0

func ExecDuration1[T any](fn func() T) (T, time.Duration)

ExecDuration1 measures time duration of running a function

func ExecDuration2 added in v1.10.0

func ExecDuration2[T1, T2 any](fn func() (T1, T2)) (T1, T2, time.Duration)

ExecDuration2 measures time duration of running a function

func ExecDuration3 added in v1.10.0

func ExecDuration3[T1, T2, T3 any](fn func() (T1, T2, T3)) (T1, T2, T3, time.Duration)

ExecDuration3 measures time duration of running a function

func ExecRetry added in v1.17.0

func ExecRetry(
	fn func() error,
	maxRetries int,
	delay time.Duration,
	options ...ExecRetryOption,
) error

func ExecRetry2 added in v1.17.0

func ExecRetry2[T any](
	fn func() (T, error),
	maxRetries int,
	delay time.Duration,
	options ...ExecRetryOption,
) (T, error)

func ExecRetry3 added in v1.17.0

func ExecRetry3[T1, T2 any](
	fn func() (T1, T2, error),
	maxRetries int,
	delay time.Duration,
	options ...ExecRetryOption,
) (T1, T2, error)

func ExecRetry4 added in v1.17.0

func ExecRetry4[T1, T2, T3 any](
	fn func() (T1, T2, T3, error),
	maxRetries int,
	delay time.Duration,
	options ...ExecRetryOption,
) (T1, T2, T3, error)

func ExecRetry5 added in v1.17.0

func ExecRetry5[T1, T2, T3, T4 any](
	fn func() (T1, T2, T3, T4, error),
	maxRetries int,
	delay time.Duration,
	options ...ExecRetryOption,
) (T1, T2, T3, T4, error)

func ExecRetryCtx added in v1.17.0

func ExecRetryCtx(
	ctx context.Context,
	fn func() error,
	maxRetries int,
	delay time.Duration,
	options ...ExecRetryOption,
) error

func ExecRetryCtx2 added in v1.17.0

func ExecRetryCtx2[T any](
	ctx context.Context,
	fn func() (T, error),
	maxRetries int,
	delay time.Duration,
	options ...ExecRetryOption,
) (T, error)

func ExecRetryCtx3 added in v1.17.0

func ExecRetryCtx3[T1, T2 any](
	ctx context.Context,
	fn func() (T1, T2, error),
	maxRetries int,
	delay time.Duration,
	options ...ExecRetryOption,
) (T1, T2, error)

func ExecRetryCtx4 added in v1.17.0

func ExecRetryCtx4[T1, T2, T3 any](
	ctx context.Context,
	fn func() (T1, T2, T3, error),
	maxRetries int,
	delay time.Duration,
	options ...ExecRetryOption,
) (T1, T2, T3, error)

func ExecRetryCtx5 added in v1.17.0

func ExecRetryCtx5[T1, T2, T3, T4 any](
	ctx context.Context,
	fn func() (T1, T2, T3, T4, error),
	maxRetries int,
	delay time.Duration,
	options ...ExecRetryOption,
) (T1, T2, T3, T4, error)

func ExecTaskFunc added in v1.9.0

func ExecTaskFunc[T any](
	ctx context.Context,
	maxConcurrentTasks uint,
	taskFunc func(ctx context.Context, obj T) error,
	targetObjects ...T,
) error

ExecTaskFunc executes a function on every target objects

func ExecTaskFuncEx added in v1.9.0

func ExecTaskFuncEx[T any](
	ctx context.Context,
	maxConcurrentTasks uint,
	stopOnError bool,
	taskFunc func(ctx context.Context, obj T) error,
	targetObjects ...T,
) map[int]error

ExecTaskFuncEx executes a function on every target objects

func ExecTasks added in v1.6.0

func ExecTasks(
	ctx context.Context,
	maxConcurrentTasks uint,
	tasks ...func(ctx context.Context) error,
) error

ExecTasks calls ExecTasksEx with stopOnError is true

func ExecTasksEx added in v1.6.0

func ExecTasksEx(
	ctx context.Context,
	maxConcurrentTasks uint,
	stopOnError bool,
	tasks ...func(ctx context.Context) error,
) map[int]error

ExecTasksEx execute multiple tasks concurrently using Go routines maxConcurrentTasks behaves similarly as `pool size`, pass 0 to set no limit. In case you want to cancel the execution, use context.WithTimeout() or context.WithCancel(). nolint: gocognit

func FastRemove

func FastRemove[T comparable, S ~[]T](ps *S, v T) bool

FastRemove removes element value

func FastRemoveAt

func FastRemoveAt[T any, S ~[]T](ps *S, i int)

FastRemoveAt removes element at the specified index by swapping it with the last item in slice

func FastRemoveLastOf

func FastRemoveLastOf[T comparable, S ~[]T](ps *S, v T) bool

FastRemoveLastOf removes element value

func Fill

func Fill[T any, S ~[]T](a S, val T)

Fill sets slice element values

func Filter

func Filter[T any, S ~[]T](s S, filterFunc func(t T) bool) S

Filter filters slice elements with condition.

func FilterGT

func FilterGT[T NumberExt | StringExt, S ~[]T](s S, v T) S

FilterGT returns all values which are greater than the specified value

func FilterGTE

func FilterGTE[T NumberExt | StringExt, S ~[]T](s S, v T) S

FilterGTE returns all values which are greater than or equal to the specified value

func FilterILIKE

func FilterILIKE[T StringExt, S ~[]T](s S, v string) S

FilterILIKE returns all strings which contain the specified substring with case-insensitive

func FilterIN

func FilterIN[T comparable, S ~[]T](s S, v ...T) S

FilterIN returns all values which are present in the specified list

func FilterLIKE

func FilterLIKE[T StringExt, S ~[]T](s S, v string) S

FilterLIKE returns all strings which contain the specified substring. Don't use wildcard in the input string. For example: FilterLIKE(names, "tom").

func FilterLT

func FilterLT[T NumberExt | StringExt, S ~[]T](s S, v T) S

FilterLT returns all values which are less than the specified value

func FilterLTE

func FilterLTE[T NumberExt | StringExt, S ~[]T](s S, v T) S

FilterLTE returns all values which are less than or equal to the specified value

func FilterNE

func FilterNE[T comparable, S ~[]T](s S, v T) S

FilterNE returns all values which are not equal to the specified value

func FilterNIN

func FilterNIN[T comparable, S ~[]T](s S, v ...T) S

FilterNIN returns all values which are not present in the specified list

func FilterPtr

func FilterPtr[T any, S ~[]T](s S, filterFunc func(t *T) bool) S

FilterPtr filters slice elements using pointer in callback. This function is faster than Filter() when used on slices of structs.

func FilterRange added in v1.15.0

func FilterRange[T NumberExt | StringExt, S ~[]T](s S, min, max T) S

FilterRange returns all values which are in the specified range (lower and upper bound inclusive)

func Find added in v1.10.0

func Find[T any, S ~[]T](a S, pred func(t T) bool) (t T, found bool)

Find finds value in slice by predicate

func FindDuplicates added in v1.11.0

func FindDuplicates[T comparable, S ~[]T](s S) S

FindDuplicates finds all elements that are duplicated in the given slice.

func FindDuplicatesBy added in v1.11.0

func FindDuplicatesBy[T any, U comparable, S ~[]T](s S, keyFunc func(T) U) S

FindDuplicatesBy finds all elements that are duplicated in the given slice.

func FindEx added in v1.15.0

func FindEx[T any, V any, S ~[]T](a S, pred func(t T) (V, bool)) (v V, found bool)

FindEx finds value in slice with returning value decided by the given function

func FindLast added in v1.10.0

func FindLast[T any, S ~[]T](a S, pred func(t T) bool) (t T, found bool)

FindLast finds value in slice from the end by predicate

func FindLastEx added in v1.15.0

func FindLastEx[T any, V any, S ~[]T](a S, pred func(t T) (V, bool)) (v V, found bool)

FindLastEx finds value in slice from the end with returning value decided by the given function

func FindLastPtr added in v1.10.0

func FindLastPtr[T any, S ~[]T](a S, pred func(t *T) bool) (t T, found bool)

FindLastPtr finds value in slice from the end by predicate

func FindPtr added in v1.10.0

func FindPtr[T any, S ~[]T](a S, pred func(t *T) bool) (t T, found bool)

FindPtr finds value in slice by predicate

func FindUniques added in v1.11.0

func FindUniques[T comparable, S ~[]T](s S) S

FindUniques finds all elements that are unique in the given slice.

func FindUniquesBy added in v1.11.0

func FindUniquesBy[T any, U comparable, S ~[]T](s S, keyFunc func(T) U) S

FindUniquesBy finds all elements that are unique in the given slice.

func First added in v1.11.0

func First[T any, S ~[]T](s S) (T, bool)

First returns the first item in slice. Returns zero value and `false` if the slice is empty.

func FirstNonEmpty added in v1.11.0

func FirstNonEmpty[T any](args ...T) (val T)

FirstNonEmpty returns the first non-empty value in the given arguments if found, otherwise returns the zero value. This function use reflection.

Non-empty value must be not:

  • zero value (0, "", nil, false)
  • empty slice, array, map, channel
  • pointer points to zero value

func FirstOr added in v1.11.0

func FirstOr[T any, S ~[]T](s S, defaultVal T) T

FirstOr gets the first item in slice. Returns the default value if slice is empty.

func Flatten

func Flatten[T any, S ~[]T](s ...S) S

Flatten flattens 2-dimensional slices. E.g. Flatten([1,2,3], [3,4,5]) -> [1,2,3,3,4,5].

func Flatten3

func Flatten3[T any, S ~[]T, SS ~[]S](s ...SS) S

Flatten3 flattens 3-dimensional slices

func ForEach

func ForEach[T any, S ~[]T](s S, pred func(i int, t T))

ForEach iterates over slice items. For more advanced requirements, see Iter.

func ForEachPtr

func ForEachPtr[T any, S ~[]T](s S, pred func(i int, t *T))

ForEachPtr iterates over pointers to slice items. You can use this to achieve more performance if you have a slice of big structs. For more advanced requirements, see IterPtr.

func ForEachPtrReverse added in v1.10.0

func ForEachPtrReverse[T any, S ~[]T](s S, pred func(i int, t *T))

ForEachPtrReverse iterates over pointers to slice items from the end. For more advanced requirements, see IterPtrReverse.

func ForEachReverse

func ForEachReverse[T any, S ~[]T](s S, pred func(i int, t T))

ForEachReverse iterates over slice items from the end. For more advanced requirements, see IterReverse.

func FormatFloat

func FormatFloat[T FloatExt](v T) string

func FormatFloatEx

func FormatFloatEx[T FloatExt](v T, format string) string

func FormatFloatGroup

func FormatFloatGroup[T FloatExt](v T) string

FormatFloatGroup format the value then group the decimal using comma

func FormatFloatGroupEx

func FormatFloatGroupEx[T FloatExt](v T, format string) string

FormatFloatGroupEx format the value then group the decimal using comma

func FormatInt

func FormatInt[T IntExt](v T) string

func FormatIntEx

func FormatIntEx[T IntExt](v T, format string) string

func FormatIntGroup

func FormatIntGroup[T IntExt](v T) string

FormatIntGroup format the value then group the decimal using comma

func FormatUint

func FormatUint[T UIntExt](v T) string

func FormatUintEx

func FormatUintEx[T UIntExt](v T, format string) string

func FormatUintGroup

func FormatUintGroup[T UIntExt](v T) string

FormatUintGroup format the value then group the decimal using comma

func Head[T any](t T, s ...any) T

Head returns the first argument

func If

func If[C bool, T any](cond C, v1 T, v2 T) T

If returns the 2nd arg if the condition is true, 3rd arg otherwise. This is similar to C-language ternary operation (cond ? val1 : val2).

NOTE: this function may cause unexpected behavior upon misuses. For example: gofn.If(len(slice) > 0, slice[0], defaultVal) will crash if slice is empty

func IndexOf

func IndexOf[T comparable, S ~[]T](a S, t T) int

IndexOf gets index of item in slice. Returns -1 if not found.

func IndexOfBy added in v1.10.0

func IndexOfBy[T any, S ~[]T](a S, pred func(t T) bool) int

IndexOfBy gets index of item in slice by predicate. Returns -1 if not found.

func IndexOfSlice

func IndexOfSlice[T comparable, S ~[]T](a, sub S) int

IndexOfSlice gets index of sub-slice in slice. Returns -1 if not found.

func Intersection

func Intersection[T comparable, S ~[]T](a, b S) S

Intersection returns all unique shared values from multiple slices

func IntersectionBy added in v1.10.0

func IntersectionBy[T any, K comparable, S ~[]T](a, b S, keyFunc func(t T) K) S

IntersectionBy returns all unique shared values from multiple slices with key function

func IsSorted

func IsSorted[T NumberExt | StringExt, S ~[]T](s S) bool

IsSorted checks if a slice is sorted

func IsSortedDesc

func IsSortedDesc[T NumberExt | StringExt, S ~[]T](s S) bool

IsSortedDesc checks if a slice is sorted in descending order

func IsUnique

func IsUnique[T comparable, S ~[]T](s S) bool

IsUnique checks a slice for uniqueness

func IsUniqueBy added in v1.10.0

func IsUniqueBy[T any, U comparable, S ~[]T](s S, keyFunc func(t T) U) bool

IsUniqueBy checks a slice for uniqueness using key function

func Iter added in v1.10.0

func Iter[T any, S ~[]T](iterFunc func(index int, v T) bool, slices ...S)

Iter iterates over items from multiple slices with ability to stop. When the `iterFunc` function returns false, the iteration stops.

func IterPtr added in v1.10.0

func IterPtr[T any, S ~[]T](iterFunc func(index int, v *T) bool, slices ...S)

IterPtr iterates over pointers to items from multiple slices with ability to stop. When the `iterFunc` function returns false, the iterating stops.

func IterPtrReverse added in v1.10.0

func IterPtrReverse[T any, S ~[]T](iterFunc func(index int, v *T) bool, slices ...S)

IterPtrReverse iterates over pointers to items from multiple slices with ability to stop. When the `iterFunc` function returns false, the iteration stops.

func IterReverse added in v1.10.0

func IterReverse[T any, S ~[]T](iterFunc func(index int, v T) bool, slices ...S)

IterReverse iterates over items from multiple slices from the end with ability to stop. When the `iterFunc` function returns false, the iteration stops.

func Last added in v1.11.0

func Last[T any, S ~[]T](s S) (T, bool)

Last returns the last item in slice. Returns zero value and `false` if the slice is empty.

func LastIndexOf

func LastIndexOf[T comparable, S ~[]T](a S, t T) int

LastIndexOf gets index of item from the end in slice. Returns -1 if not found.

func LastIndexOfBy added in v1.10.0

func LastIndexOfBy[T any, S ~[]T](a S, pred func(t T) bool) int

LastIndexOfBy gets index of item from the end in slice. Returns -1 if not found.

func LastIndexOfSlice

func LastIndexOfSlice[T comparable, S ~[]T](a, sub S) int

LastIndexOfSlice gets last index of sub-slice in slice Returns -1 if not found

func LastOr added in v1.11.0

func LastOr[T any, S ~[]T](s S, defaultVal T) T

LastOr gets the last item in slice. Returns the default value if slice is empty.

func LinesTrim

func LinesTrim(s string, cutset string) string

LinesTrim trim leading and trailing characters for every line in the given string. Deprecated

func LinesTrimLeft

func LinesTrimLeft(s string, cutset string) string

LinesTrimLeft trim leading characters for every line in the given string. Deprecated

func LinesTrimLeftSpace

func LinesTrimLeftSpace(s string) string

LinesTrimLeftSpace trim leading spaces for every line in the given string. Deprecated

func LinesTrimRight

func LinesTrimRight(s string, cutset string) string

LinesTrimRight trim trailing characters for every line in the given string. Deprecated

func LinesTrimRightSpace

func LinesTrimRightSpace(s string) string

LinesTrimRightSpace trim trailing characters for every line in the given string. Deprecated

func LinesTrimSpace

func LinesTrimSpace(s string) string

LinesTrimSpace trim leading and trailing spaces for every line in the given string. Deprecated

func MapContainKeys

func MapContainKeys[K comparable, V any, M ~map[K]V](m M, keys ...K) bool

MapContainKeys tests if a map contains one or more keys

func MapContainValues

func MapContainValues[K comparable, V comparable, M ~map[K]V](m M, values ...V) bool

MapContainValues tests if a map contains one or more values (complexity is O(n)). If you often need to check existence of map value, consider using bi-map data structure.

func MapCopy added in v1.5.0

func MapCopy[K comparable, V any, M ~map[K]V](m M) M

MapCopy returns a copied a map

func MapDifferenceKeys

func MapDifferenceKeys[K comparable, V any, M ~map[K]V](m1, m2 M) ([]K, []K)

MapDifferenceKeys returns 2 lists of keys that are differences of 2 maps

func MapEqual

func MapEqual[K comparable, V comparable, M ~map[K]V](m1, m2 M) bool

MapEqual compares contents of 2 maps

func MapEqualBy added in v1.10.0

func MapEqualBy[K comparable, V any, M ~map[K]V](m1, m2 M, equalCmp func(v1, v2 V) bool) bool

MapEqualBy compares contents of 2 maps

func MapGet

func MapGet[K comparable, V any, M ~map[K]V](m M, k K, defaultVal V) V

MapGet gets the value for the key, if not exist, returns the default one

func MapIntersectionKeys

func MapIntersectionKeys[K comparable, V any, M ~map[K]V](m1 M, ms ...M) []K

MapIntersectionKeys returns a list of unique keys that exist in all maps

func MapIter added in v1.14.0

func MapIter[K comparable, V any, M ~map[K]V](iterFunc func(K, V), mapSlice ...M)

MapIter iterates over entries of multiple maps

func MapKeys

func MapKeys[K comparable, V any, M ~map[K]V](m M) []K

MapKeys gets map keys as slice

func MapOmit added in v1.9.0

func MapOmit[K comparable, V any, M ~map[K]V](m M, keys ...K)

MapOmit omits keys from a map

func MapOmitCopy added in v1.9.0

func MapOmitCopy[K comparable, V any, M ~map[K]V](m M, keys ...K) M

MapOmitCopy returns a new map with omitting the specified keys

func MapPick added in v1.9.0

func MapPick[K comparable, V any, M ~map[K]V](m M, keys ...K) M

MapPick returns a new map with picking up the specified keys only

func MapPop

func MapPop[K comparable, V any, M ~map[K]V](m M, k K, defaultVal V) V

MapPop deletes and returns the value of the key if exists, returns the default one if not

func MapReverse added in v1.13.0

func MapReverse[K comparable, V comparable, M ~map[K]V, M2 map[V]K](m M) (M2, []K)

MapReverse reverses a map by exchanging its keys and values.

func MapSetDefault

func MapSetDefault[K comparable, V any, M ~map[K]V](m M, k K, defaultVal V) V

MapSetDefault sets default value for a key and returns the current value

func MapSlice

func MapSlice[T any, U any, S ~[]T](s S, mapFunc func(T) U) []U

MapSlice transforms a slice to another with map function

func MapSliceEx

func MapSliceEx[T any, U any, S ~[]T](s S, mapFunc func(T) (U, error)) ([]U, error)

MapSliceEx transforms a slice to another with map function and error handling

func MapSliceToMap

func MapSliceToMap[T any, K comparable, V any, S ~[]T](s S, mapFunc func(T) (K, V)) map[K]V

MapSliceToMap transforms a slice to a map with map function

func MapSliceToMapEx

func MapSliceToMapEx[T any, K comparable, V any, S ~[]T](s S, mapFunc func(T) (K, V, error)) (map[K]V, error)

MapSliceToMapEx transforms a slice to a map with map function and error handling

func MapSliceToMapKeys added in v1.9.0

func MapSliceToMapKeys[T comparable, V any, S ~[]T](s S, defaultVal V) map[T]V

MapSliceToMapKeys transforms a slice to a map using slice items as map keys. For example: MapSliceToMapKeys(s, struct{}{}) -> map[T]struct{}

func MapUnionKeys

func MapUnionKeys[K comparable, V any, M ~map[K]V](m1 M, ms ...M) []K

MapUnionKeys returns a list of unique keys that are collected from multiple maps

func MapUpdate

func MapUpdate[K comparable, V any, M ~map[K]V](m1, m2 M) M

MapUpdate merges map content with another map. Not change the target map, only change the source map.

func MapUpdateExistingOnly

func MapUpdateExistingOnly[K comparable, V any, M ~map[K]V](m1, m2 M) M

MapUpdateExistingOnly update map existing items with another map. Not change the target map, only change the source map.

func MapUpdateNewOnly

func MapUpdateNewOnly[K comparable, V any, M ~map[K]V](m1, m2 M) M

MapUpdateNewOnly update map with another map and not override the existing values. Not change the target map, only change the source map.

func MapValues

func MapValues[K comparable, V any](m map[K]V) []V

MapValues gets map values as slice

func Max

func Max[T NumberExt | StringExt](v1 T, s ...T) T

Max find the maximum value in the list

func MaxIn

func MaxIn[T NumberExt | StringExt, S ~[]T](s S) (T, error)

MaxIn finds the maximum value in the list. Use max := Must(MaxIn(slice)) to panic on error.

func MaxInBy added in v1.10.0

func MaxInBy[T any, S ~[]T](s S, lessFunc func(a, b T) bool) (T, error)

MaxInBy finds the maximum value in the list

func MaxTime

func MaxTime(t1 time.Time, s ...time.Time) time.Time

MaxTime finds the maximum time in the list

func Min

func Min[T NumberExt | StringExt](v1 T, s ...T) T

Min find the minimum value in the list

func MinIn

func MinIn[T NumberExt | StringExt, S ~[]T](s S) (T, error)

MinIn find the minimum value in the list. Use min := Must(MinIn(slice)) to panic on error.

func MinInBy added in v1.10.0

func MinInBy[T any, S ~[]T](s S, lessFunc func(a, b T) bool) (T, error)

MinInBy find the minimum value in the list

func MinMax

func MinMax[T NumberExt | StringExt](v1 T, s ...T) (T, T)

MinMax finds the minimum and maximum values in the list

func MinMaxTime

func MinMaxTime(t1 time.Time, s ...time.Time) (time.Time, time.Time)

MinMaxTime gets the minimum and maximum time values in the list

func MinTime

func MinTime(t1 time.Time, s ...time.Time) time.Time

MinTime finds the minimum time in the list. NOTE: if zero time is in the list, the result will be zero.

func Must

func Must[T any](v T, e error) T

Must is the same as Must2

func Must1

func Must1(e error)

func Must2

func Must2[T any](v T, e error) T

func Must3

func Must3[T1, T2 any](v1 T1, v2 T2, e error) (T1, T2)

func Must4

func Must4[T1, T2, T3 any](v1 T1, v2 T2, v3 T3, e error) (T1, T2, T3)

func Must5

func Must5[T1, T2, T3, T4 any](v1 T1, v2 T2, v3 T3, v4 T4, e error) (T1, T2, T3, T4)

func Must6

func Must6[T1, T2, T3, T4, T5 any](v1 T1, v2 T2, v3 T3, v4 T4, v5 T5, e error) (T1, T2, T3, T4, T5)

func NumberFmtGroup

func NumberFmtGroup(num string, fractionSep, groupSep byte) string

NumberFmtGroup separate decimal groups in the value string

func NumberFmtUngroup

func NumberFmtUngroup(num string, groupSep byte) string

NumberFmtUngroup ungroup the value string

func ParseFloat

func ParseFloat[T FloatExt](s string) (T, error)

func ParseFloatDef

func ParseFloatDef[T FloatExt](s string, defaultVal T) T

func ParseFloatUngroup

func ParseFloatUngroup[T FloatExt](s string) (T, error)

ParseFloatUngroup omit all grouping commas then parse the string value

func ParseInt

func ParseInt[T IntExt](s string) (T, error)

func ParseIntDef

func ParseIntDef[T IntExt](s string, defaultVal T) T

func ParseIntEx

func ParseIntEx[T IntExt](s string, base int) (T, error)

func ParseIntUngroup

func ParseIntUngroup[T IntExt](s string) (T, error)

ParseIntUngroup omit all grouping commas then parse the string value

func ParseUint

func ParseUint[T UIntExt](s string) (T, error)

func ParseUintDef

func ParseUintDef[T UIntExt](s string, defaultVal T) T

func ParseUintEx

func ParseUintEx[T UIntExt](s string, base int) (T, error)

func ParseUintUngroup

func ParseUintUngroup[T UIntExt](s string) (T, error)

ParseUintUngroup omit all grouping commas then parse the string value

func Partial2Arg0Ret added in v1.13.0

func Partial2Arg0Ret[A1 any, A2 any](fn func(A1, A2), a1 A1) func(A2)

func Partial2Arg1Ret added in v1.13.0

func Partial2Arg1Ret[A1 any, A2 any, R1 any](fn func(A1, A2) R1, a1 A1) func(A2) R1

func Partial2Arg2Ret added in v1.13.0

func Partial2Arg2Ret[A1 any, A2 any, R1 any, R2 any](fn func(A1, A2) (R1, R2), a1 A1) func(A2) (R1, R2)

func Partial2Arg3Ret added in v1.13.0

func Partial2Arg3Ret[A1 any, A2 any, R1 any, R2 any, R3 any](fn func(A1, A2) (R1, R2, R3), a1 A1) func(A2) (R1, R2, R3)

nolint: lll

func Partial3Arg0Ret added in v1.13.0

func Partial3Arg0Ret[A1 any, A2 any, A3 any](fn func(A1, A2, A3), a1 A1) func(A2, A3)

func Partial3Arg1Ret added in v1.13.0

func Partial3Arg1Ret[A1 any, A2 any, A3 any, R1 any](fn func(A1, A2, A3) R1, a1 A1) func(A2, A3) R1

func Partial3Arg2Ret added in v1.13.0

func Partial3Arg2Ret[A1 any, A2 any, A3 any, R1 any, R2 any](fn func(A1, A2, A3) (R1, R2), a1 A1) func(A2, A3) (R1, R2)

nolint: lll

func Partial3Arg3Ret added in v1.13.0

func Partial3Arg3Ret[A1 any, A2 any, A3 any, R1 any, R2 any, R3 any](fn func(A1, A2, A3) (R1, R2, R3), a1 A1) func(A2, A3) (R1, R2, R3)

nolint: lll

func Partial4Arg0Ret added in v1.13.0

func Partial4Arg0Ret[A1 any, A2 any, A3 any, A4 any](fn func(A1, A2, A3, A4), a1 A1) func(A2, A3, A4)

func Partial4Arg1Ret added in v1.13.0

func Partial4Arg1Ret[A1 any, A2 any, A3 any, A4 any, R1 any](fn func(A1, A2, A3, A4) R1, a1 A1) func(A2, A3, A4) R1

nolint: lll

func Partial4Arg2Ret added in v1.13.0

func Partial4Arg2Ret[A1 any, A2 any, A3 any, A4 any, R1 any, R2 any](fn func(A1, A2, A3, A4) (R1, R2), a1 A1) func(A2, A3, A4) (R1, R2)

nolint: lll

func Partial4Arg3Ret added in v1.13.0

func Partial4Arg3Ret[A1 any, A2 any, A3 any, A4 any, R1 any, R2 any, R3 any](fn func(A1, A2, A3, A4) (R1, R2, R3), a1 A1) func(A2, A3, A4) (R1, R2, R3)

nolint: lll

func Partial5Arg0Ret added in v1.13.0

func Partial5Arg0Ret[A1 any, A2 any, A3 any, A4 any, A5 any](fn func(A1, A2, A3, A4, A5), a1 A1) func(A2, A3, A4, A5)

nolint: lll

func Partial5Arg1Ret added in v1.13.0

func Partial5Arg1Ret[A1 any, A2 any, A3 any, A4 any, A5 any, R1 any](fn func(A1, A2, A3, A4, A5) R1, a1 A1) func(A2, A3, A4, A5) R1

nolint: lll

func Partial5Arg2Ret added in v1.13.0

func Partial5Arg2Ret[A1 any, A2 any, A3 any, A4 any, A5 any, R1 any, R2 any](fn func(A1, A2, A3, A4, A5) (R1, R2), a1 A1) func(A2, A3, A4, A5) (R1, R2)

nolint: lll

func Partial5Arg3Ret added in v1.13.0

func Partial5Arg3Ret[A1 any, A2 any, A3 any, A4 any, A5 any, R1 any, R2 any, R3 any](fn func(A1, A2, A3, A4, A5) (R1, R2, R3), a1 A1) func(A2, A3, A4, A5) (R1, R2, R3)

nolint: lll

func Partition added in v1.9.0

func Partition[T any, S ~[]T](s S, partitionFunc func(T, int) bool) (S, S)

Partition splits slice items into 2 lists.

func PartitionN added in v1.9.0

func PartitionN[T any, S ~[]T](s S, numPartitions uint, partitionFunc func(T, int) int) []S

PartitionN splits slice items into N lists. partitionFunc should return index of the partition to put the corresponding item into.

func Product

func Product[T NumberExt | ComplexExt](s ...T) T

Product calculates product value of slice elements

func ProductAs

func ProductAs[U, T NumberExt](s ...T) U

ProductAs calculates product value with conversion to another type. Type size of the result should be wider than the input's. E.g. product := ProductAs[int64](int32Slice...)

func PtrValueOrEmpty added in v1.16.0

func PtrValueOrEmpty[T any](t *T) (val T)

PtrValueOrEmpty returns the value of the pointer var, if it's nil returns empty value

func RandChoice added in v1.8.0

func RandChoice[T any](s ...T) (T, bool)

RandChoice picks up an item randomly from a slice

func RandString

func RandString(n int) string

RandString generates a random string

func RandStringEx

func RandStringEx[S ~[]rune](n int, allowedChars S) string

RandStringEx generates a random string

func RandToken added in v1.15.0

func RandToken(length int) []byte

RandToken generates a random token which can be used for crypto purpose

func RandTokenAsHex added in v1.15.0

func RandTokenAsHex(length int) string

RandTokenAsHex generates a random token as hex string

func Reduce

func Reduce[T any, S ~[]T](s S, reduceFunc func(accumulator, currentValue T) T) T

Reduce reduces a slice to a value

func ReduceEx

func ReduceEx[T any, U any, S ~[]T](
	s S,
	reduceFunc func(accumulator U, currentValue T, currentIndex int) U,
	initVal U,
) U

ReduceEx reduces a slice to a value with custom initial value

func ReduceReverse added in v1.11.0

func ReduceReverse[T any, S ~[]T](s S, reduceFunc func(accumulator, currentValue T) T) T

ReduceReverse reduces a slice to a value

func ReduceReverseEx added in v1.11.0

func ReduceReverseEx[T any, U any, S ~[]T](
	s S,
	reduceFunc func(accumulator U, currentValue T, currentIndex int) U,
	initVal U,
) U

ReduceReverseEx reduces a slice to a value with custom initial value

func Remove

func Remove[T comparable, S ~[]T](ps *S, v T) bool

Remove removes element value

func RemoveAll

func RemoveAll[T comparable, S ~[]T](ps *S, v T) int

RemoveAll removes all occurrences of value

func RemoveAt

func RemoveAt[T any, S ~[]T](ps *S, i int)

RemoveAt removes element at the specified index

func RemoveLastOf

func RemoveLastOf[T comparable, S ~[]T](ps *S, v T) bool

RemoveLastOf removes element value

func Replace

func Replace[T comparable, S ~[]T](s S, value, replacement T) bool

Replace replaces a value in slice with another value

func ReplaceAll

func ReplaceAll[T comparable, S ~[]T](s S, value, replacement T) int

ReplaceAll replaces a value in slice with another value

func ReplaceN added in v1.10.0

func ReplaceN[T comparable, S ~[]T](s S, value, replacement T, n int) int

ReplaceN replaces a value in slice for the first n-occurrences

func Reverse

func Reverse[T any, S ~[]T](s S) S

Reverse reverses slice content, this modifies the slice

func ReverseCopy

func ReverseCopy[T any, S ~[]T](s S) S

ReverseCopy returns a new slice which has content in reversed order

func Shuffle added in v1.8.0

func Shuffle[T any, S ~[]T](s S, randFuncs ...func(n int) int) S

Shuffle items of a slice and returns a new slice

func SliceByRange added in v1.6.0

func SliceByRange[T NumberExt](start, end, step T) []T

SliceByRange generates a slice by range. start is inclusive, end is exclusive.

func Sort

func Sort[T NumberExt | StringExt, S ~[]T](s S) S

Sort sorts slice values

func SortDesc

func SortDesc[T NumberExt | StringExt, S ~[]T](s S) S

SortDesc sorts slice values in descending order

func SortEx

func SortEx[T any, S ~[]T](s S, less func(i, j int) bool) S

SortEx sorts slice values

func SortStable

func SortStable[T NumberExt | StringExt, S ~[]T](s S) S

SortStable sorts slice values

func SortStableDesc

func SortStableDesc[T NumberExt | StringExt, S ~[]T](s S) S

SortStableDesc sorts slice values in descending order

func SortStableEx

func SortStableEx[T any, S ~[]T](s S, less func(i, j int) bool) S

SortStableEx sorts slice values

func Splice added in v1.13.0

func Splice[T any, S ~[]T](s S, start, deleteCount int, newItems ...T) S

Splice removes a portion of the given slice and inserts elements of another slice into that position.

func SpliceEx added in v1.13.0

func SpliceEx[T any, S ~[]T](s S, start, deleteCount int, newItems ...T) (S, S)

SpliceEx removes a portion of the given slice and inserts elements of another slice into that position. This function returns a new slice at the 1st place, the 2nd is the deleted elements.

func StringJoin

func StringJoin[T any, S ~[]T](s S, sep string) string

StringJoin join elements from a slice of any type. This function calls fmt.Sprintf("%v", elem) to format every element.

func StringJoinBy added in v1.10.0

func StringJoinBy[T any, S ~[]T](s S, sep string, fmtFunc func(v T) string) string

StringJoinBy join elements from a slice of any type with custom format function

func StringJoinEx

func StringJoinEx[T any, S ~[]T](s S, sep, format string) string

StringJoinEx join elements from a slice of any type with custom format string

func StringLexJoin added in v1.11.0

func StringLexJoin[T any, S ~[]T](s S, sep, lastSep string) string

StringLexJoin lexical joins a list of items of any type.

func StringLexJoinEx added in v1.11.0

func StringLexJoinEx[T any, S ~[]T](s S, sep, lastSep, format string) string

StringLexJoinEx lexical joins a list of items of any type. The input format will be used with fmt.Sprintf() to render slice items as string.

For example:

StringLexJoinEx(["grape", "apple", "orange"], ", ", " and ", "%v") -> grape, apple and orange
StringLexJoinEx(["grape", "apple", "orange"], ", ", " or ", "%v") -> grape, apple or orange

func StringSplit added in v1.15.0

func StringSplit(s string, sep, quote string) (res []string)

StringSplit splits a string with handling quotes. `quote` param can be a single char (`"`, `'`...) if opening and closing tokens are the same, or a space-delimited string (`{ }`, `[ ]`, `{{ }}`...) if the tokens are different.

func StringSplitN added in v1.15.0

func StringSplitN(s string, sep, quote string, n int) (res []string)

StringSplitN splits a string with handling quotes. `quote` param can be a single char (`"`, `'`...) if opening and closing tokens are the same, or a space-delimited string (`{ }`, `[ ]`, `{{ }}`...) if the tokens are different.

func StringToLower1stLetter added in v1.15.0

func StringToLower1stLetter(s string) string

StringToLower1stLetter lowercases the first letter of the input string

func StringToUpper1stLetter added in v1.15.0

func StringToUpper1stLetter(s string) string

StringToUpper1stLetter uppercases the first letter of the input string

func StringUnwrap added in v1.12.0

func StringUnwrap(s string, token string) string

StringUnwrap unwraps a string wrapped with the given token

func StringUnwrapLR added in v1.12.0

func StringUnwrapLR(s string, tokenLeft, tokenRight string) string

StringUnwrapLR unwraps a string wrapped with the given tokens

func StringWrap added in v1.12.0

func StringWrap(s string, token string) string

StringWrap wraps a string with the given token

func StringWrapLR added in v1.12.0

func StringWrapLR(s string, tokenLeft, tokenRight string) string

StringWrapLR wraps a string with the given tokens for the left and right side

func SubSlice added in v1.6.0

func SubSlice[T any, S ~[]T](s S, start, end int) S

SubSlice gets sub slice from a slice. Passing negative numbers to get items from the end of the slice. For example, using start=-1, end=-2 to get the last item of the slice end param is exclusive.

func Sum

func Sum[T NumberExt | ComplexExt](s ...T) T

Sum calculates sum of slice items

func SumAs

func SumAs[U, T NumberExt](s ...T) U

SumAs calculates sum value with conversion to another type. Type size of the result should be wider than the input's. E.g. sum := SumAs[int64](int32Slice...)

func Tail

func Tail[T any](t any, s ...any) (T, bool)

Tail returns the last argument

func ToIfaceSlice added in v1.10.0

func ToIfaceSlice[T any, S ~[]T](s S) []any

ToIfaceSlice convert a slice to a slice of interface

func ToNumberSlice

func ToNumberSlice[U, T NumberExt, S ~[]T](slice S) []U

ToNumberSlice converts int-approximate slice to int slice

func ToPtr added in v1.11.0

func ToPtr[T any](t T) *T

ToPtr returns pointer to the address of the input

func ToPtrSlice added in v1.11.0

func ToPtrSlice[T any, S ~[]T](s S) []*T

ToPtrSlice returns a slice of pointers point to the input slice's elements

func ToSafeInt8 added in v1.12.0

func ToSafeInt8[T IntExt | UIntExt](v T) (int8, error)

ToSafeInt8 safely cast the value to type int8 (not using reflection)

func ToSafeInt16 added in v1.12.0

func ToSafeInt16[T IntExt | UIntExt](v T) (int16, error)

ToSafeInt16 safely cast the value to type int16 (not using reflection)

func ToSafeInt32 added in v1.12.0

func ToSafeInt32[T IntExt | UIntExt](v T) (int32, error)

ToSafeInt32 safely cast the value to type int32 (not using reflection)

func ToSafeInt64 added in v1.12.0

func ToSafeInt64[T IntExt | UIntExt](v T) (int64, error)

ToSafeInt64 safely cast the value to type int64 (not using reflection)

func ToSafeUint8 added in v1.12.0

func ToSafeUint8[T IntExt | UIntExt](v T) (uint8, error)

ToSafeUint8 safely cast the value to type uint8 (not using reflection)

func ToSafeUint16 added in v1.12.0

func ToSafeUint16[T IntExt | UIntExt](v T) (uint16, error)

ToSafeUint16 safely cast the value to type uint16 (not using reflection)

func ToSafeUint32 added in v1.12.0

func ToSafeUint32[T IntExt | UIntExt](v T) (uint32, error)

ToSafeUint32 safely cast the value to type uint32 (not using reflection)

func ToSafeUint64 added in v1.12.0

func ToSafeUint64[T IntExt | UIntExt](v T) (uint64, error)

ToSafeUint64 safely cast the value to type uint64 (not using reflection)

func ToSet

func ToSet[T comparable, S ~[]T](s S) S

ToSet calculates unique values of a slice

func ToSetBy added in v1.10.0

func ToSetBy[T any, K comparable, S ~[]T](s S, keyFunc func(t T) K) S

ToSetBy calculates unique values of a slice with custom key function

func ToSetByReverse added in v1.10.0

func ToSetByReverse[T any, K comparable, S ~[]T](s S, keyFunc func(t T) K) S

ToSetByReverse calculates unique values of a slice with custom key function. Unlike ToSetBy, this function iterates over the slice from the end.

func ToSlice

func ToSlice[T any](s ...T) []T

ToSlice returns a slice for individual input arguments

func ToSliceSkippingNil added in v1.15.0

func ToSliceSkippingNil[T any](values ...*T) []*T

ToSliceSkippingNil makes a slice from the given values with skipping `nil` ones

func ToSliceSkippingZero added in v1.15.0

func ToSliceSkippingZero[T comparable](values ...T) []T

ToSliceSkippingZero makes a slice from the given values with skipping `zero` ones

func ToStringSlice

func ToStringSlice[U, T ~string, S ~[]T](slice S) []U

ToStringSlice converts str-approximate slice to string slice

func Union

func Union[T comparable, S ~[]T](a, b S) S

Union returns all unique values from multiple slices

func UnionBy added in v1.10.0

func UnionBy[T any, K comparable, S ~[]T](a, b S, keyFunc func(t T) K) S

UnionBy returns all unique values from multiple slices with key function

Types

type Complex added in v1.10.0

type Complex interface {
	complex64 | complex128
}

type ComplexExt added in v1.10.0

type ComplexExt interface {
	~complex64 | ~complex128
}

type ComplexPtr added in v1.10.0

type ComplexPtr interface {
	*complex64 | *complex128
}

type ExecRetryConfig added in v1.17.0

type ExecRetryConfig struct {
	// contains filtered or unexported fields
}

type ExecRetryOption added in v1.17.0

type ExecRetryOption func(*ExecRetryConfig)

func ExecRetryCheck added in v1.17.1

func ExecRetryCheck(checkFunc func(error) bool) ExecRetryOption

func ExecRetryDelayExpoBackoff added in v1.17.0

func ExecRetryDelayExpoBackoff(jitter time.Duration) ExecRetryOption

func ExecRetryDelayIncr added in v1.17.0

func ExecRetryDelayIncr(incremental time.Duration) ExecRetryOption

func ExecRetryDelayMax added in v1.17.0

func ExecRetryDelayMax(maxDelay time.Duration) ExecRetryOption

func ExecRetryIfErrorIs added in v1.17.1

func ExecRetryIfErrorIs(errs ...error) ExecRetryOption

func ExecRetryIfErrorIsNot added in v1.17.1

func ExecRetryIfErrorIsNot(errs ...error) ExecRetryOption

type Float

type Float interface {
	float32 | float64
}

type FloatExt added in v1.9.0

type FloatExt interface {
	~float32 | ~float64
}

type FloatPtr added in v1.7.0

type FloatPtr interface {
	*float32 | *float64
}

type Int

type Int interface {
	int | int8 | int16 | int32 | int64
}

type IntExt added in v1.9.0

type IntExt interface {
	~int | ~int8 | ~int16 | ~int32 | ~int64
}

type IntPtr added in v1.7.0

type IntPtr interface {
	*int | *int8 | *int16 | *int32 | *int64
}

type Number

type Number interface {
	Int | UInt | Float
}

type NumberExt added in v1.9.0

type NumberExt interface {
	IntExt | UIntExt | FloatExt
}

type NumberPtr added in v1.7.0

type NumberPtr interface {
	IntPtr | UIntPtr | FloatPtr
}

type RandChoiceMaker added in v1.8.0

type RandChoiceMaker[T any] struct {
	// contains filtered or unexported fields
}

RandChoiceMaker a struct for picking up items randomly from a list of items

func NewRandChoiceMaker added in v1.8.0

func NewRandChoiceMaker[T any, S ~[]T](s S, randFuncs ...func(n int) int) RandChoiceMaker[T]

func (*RandChoiceMaker[T]) HasNext added in v1.8.0

func (m *RandChoiceMaker[T]) HasNext() bool

HasNext checks to see the maker has items to return

func (*RandChoiceMaker[T]) Next added in v1.8.0

func (m *RandChoiceMaker[T]) Next() (T, bool)

Next gets the next item randomly from the source. If there is no item in the source, returns false as the 2nd value.

type String added in v1.9.0

type String interface {
	string
}

type StringExt added in v1.9.0

type StringExt interface {
	~string
}

type StringPtr added in v1.7.0

type StringPtr interface {
	*string
}

type Tuple2

type Tuple2[T1, T2 any] struct {
	Elem1 T1
	Elem2 T2
}

func MapEntries

func MapEntries[K comparable, V any, M ~map[K]V](m M) []*Tuple2[K, V]

MapEntries returns a slice of map entries as Tuple2 type

func Zip

func Zip[T1, T2 any, S1 ~[]T1, S2 ~[]T2](slice1 S1, slice2 S2) []*Tuple2[T1, T2]

Zip combines values from 2 slices by each position

func (*Tuple2[T1, T2]) Unpack added in v1.11.0

func (tuple2 *Tuple2[T1, T2]) Unpack() (T1, T2)

Unpack unpacks elements of tuple, panic on nil pointer

type Tuple3

type Tuple3[T1, T2, T3 any] struct {
	Elem1 T1
	Elem2 T2
	Elem3 T3
}

func Zip3

func Zip3[T1, T2, T3 any, S1 ~[]T1, S2 ~[]T2, S3 ~[]T3](slice1 S1, slice2 S2, slice3 S3) []*Tuple3[T1, T2, T3]

Zip3 combines values from 3 slices by each position

func (*Tuple3[T1, T2, T3]) Unpack added in v1.11.0

func (tuple3 *Tuple3[T1, T2, T3]) Unpack() (T1, T2, T3)

Unpack unpacks elements of tuple, panic on nil pointer

type Tuple4 added in v1.11.0

type Tuple4[T1, T2, T3, T4 any] struct {
	Elem1 T1
	Elem2 T2
	Elem3 T3
	Elem4 T4
}

func Zip4 added in v1.11.0

func Zip4[T1, T2, T3, T4 any, S1 ~[]T1, S2 ~[]T2, S3 ~[]T3, S4 ~[]T4](
	slice1 S1, slice2 S2, slice3 S3, slice4 S4,
) []*Tuple4[T1, T2, T3, T4]

Zip4 combines values from 4 slices by each position

func (*Tuple4[T1, T2, T3, T4]) Unpack added in v1.11.0

func (tuple4 *Tuple4[T1, T2, T3, T4]) Unpack() (T1, T2, T3, T4)

Unpack unpacks elements of tuple, panic on nil pointer

type Tuple5 added in v1.11.0

type Tuple5[T1, T2, T3, T4, T5 any] struct {
	Elem1 T1
	Elem2 T2
	Elem3 T3
	Elem4 T4
	Elem5 T5
}

func Zip5 added in v1.11.0

func Zip5[T1, T2, T3, T4, T5 any, S1 ~[]T1, S2 ~[]T2, S3 ~[]T3, S4 ~[]T4, S5 ~[]T5](
	slice1 S1, slice2 S2, slice3 S3, slice4 S4, slice5 S5,
) []*Tuple5[T1, T2, T3, T4, T5]

Zip5 combines values from 4 slices by each position

func (*Tuple5[T1, T2, T3, T4, T5]) Unpack added in v1.11.0

func (tuple5 *Tuple5[T1, T2, T3, T4, T5]) Unpack() (T1, T2, T3, T4, T5)

Unpack unpacks elements of tuple, panic on nil pointer

type UInt

type UInt interface {
	uint | uint8 | uint16 | uint32 | uint64 | uintptr
}

type UIntExt added in v1.9.0

type UIntExt interface {
	~uint | ~uint8 | ~uint16 | ~uint32 | ~uint64 | ~uintptr
}

type UIntPtr added in v1.7.0

type UIntPtr interface {
	*uint | *uint8 | *uint16 | *uint32 | *uint64 | *uintptr
}

Jump to

Keyboard shortcuts

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