gofn

package module
v1.6.1 Latest Latest
Warning

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

Go to latest
Published: Nov 25, 2023 License: MIT Imports: 12 Imported by: 5

README

Go Version GoDoc Build Status Coverage Status GoReport

gofn - Utility functions for Go 1.18+

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

Functionalities

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

Try related libs:

Contents

Installation

go get github.com/tiendc/gofn

Usage

Functions for slices

Equal

Returns true if 2 slices have the same size and all elements of them equal in the current order. This function is equivalent to reflect.DeepEqual(), but faster (for how much faster, see Benchmark section).

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

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

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 ContentEqualPred for custom key function
ContentEqualPred([]string{"one", "TWO"}, []string{"two", "ONE"}, strings.ToLower) // true
Concat

Concatenates two or more slices.

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

Returns true if a slice contains a value.

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

// Use ContainPred for custom function
ContainPred([]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
IsUnique

Returns true if a slice contains unique values.

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

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

Finds a value in a slice by predicate.

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

Finds a value in a slice from the end by predicate.

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

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 IndexOfPred for custom function
IndexOfPred([]string{"one", "TWO"}, func(elem string) bool {
    return strings.ToLower(elem) == "two"
}) // 1
LastIndexOf

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

Replaces first occurrence of a value with another value.

Replace([]int{1, 2, 1, 3, 1}, 1, 11) // []int{11, 2, 1, 3, 1}
ReplaceAll

Replaces all occurrences of a value with another value.

ReplaceAll([]int{1, 2, 1, 3, 1}, 1, 11) // []int{11, 2, 11, 3, 11}
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}
CountValue

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

Returns the first element of slice if it is not empty, otherwise return the default value.

GetFirst([]int{1, 2, 3}, 4) // 1
GetFirst([]int{}, 11)       // 11
GetLast

Returns the last element of slice if it is not empty, otherwise return the default value.

GetLast([]int{1, 2, 3}, 4) // 3
GetLast([]int{}, 11)       // 11
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}
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}
Functions for maps

MapEqual

Returns true if 2 maps equal. This function is equivalent to reflect.DeepEqual(), but faster (for how much faster, see Benchmark section).

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
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)
MapUpdate/MapUpdateXX

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

Copies map content with filter keys.

m1 := map[int]int{1: 11, 2: 22, 3: 33}
m2 := MapCopy(m1, 2, 3, 4) // m2 == map[int]int{2: 22, 3: 33}
MapCopyExcludeKeys

Copies map content with excluding keys.

m1 := map[int]int{1: 11, 2: 22, 3: 33}
m2 := MapCopyExcludeKeys(m1, 2, 3, 4) // m2 == map[int]int{1: 11}
Functions for structs

StructToMap / StructToMapEx

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.

Functions for strings

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
StringJoin / StringJoinPred

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 := StringJoinPred([]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"
MultilineString

Removes all leading spaces from every line in the given string. This function is useful to declare a string with a neat multiline-style.

func DoSomething() {
	// Commonly you may use this style to create multiline string in Go (which looks ugly)
	s := `
line-1 abc xyz
line-2 abc xyz
`
	// Use this function
	s := MultilineString(
		`line-1 abc xyz
		line-2 abc xyz`
	)
}
LinesTrim/LinesTrimSpace

Removes all certain leading and trailing characters from every line in the given string.

LinesTrimSpace("  line-1  \n  line-2  ")      // "line-1\nline-2"
LinesTrim("a line-1 b \n a line-2 ab", " ba") // "line-1\nline2"
LinesTrimLeft/LinesTrimLeftSpace

Removes all certain leading characters from every line in the given string.

LinesTrimLeftSpace("  line-1  \n  line-2  ")      // "line-1  \nline-2  "
LinesTrimLeft("ab line-1  \n a line-2 ab", " ba") // "line-1  \nline2 ab"
LinesTrimRight/LinesTrimRightSpace

Removes all certain trailing characters from every line in the given string.

LinesTrimRightSpace("  line-1  \n  line-2  ")    // "  line-1\nline-2"
LinesTrimRight("line-1 b \n a line-2 ab", " ba") // "line-1\n a line2"
Functions for numbers

ParseInt/ParseIntXX

Parses integer 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/FormatIntXX

Formats an integer.

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.
Functions for concurrency

ExecTasks / ExecTasksEx

Execute 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
}
Transformation functions

Filter / FilterXX

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}
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"}
ToSet

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 ToSetPred for custom key function
ToSetPred([]string{"one", "TWO", "two", "One"}, strings.ToLower) // []string{"one", "TWO"}
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
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}}
Reverse

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

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

Combines values from multiple slices by each position.

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}}
Conversion functions

ToIntfSlice

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

ToIntfSlice([]int{1, 2, 3})         // []any{1, 2, 3}
ToIntfSlice([]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}
Bind functions

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()
Common functions

ForEach

Iterates over slice content.

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

Iterates over slice content from the end.

ForEachReverse([]int{1, 2, 3}, func (i, v int) {
    fmt.Printf("%d ", v)
}) // prints 3 2 1
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
MustN (N is from 1 to 6)

MustN functions accept a number of arguments with the last one is of error type. MustN 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
Sorting functions

Sort / SortDesc

Convenient wrapper 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
Specific Algo functions

Union

Finds all unique values from multiple slices.

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

Finds all unique shared values from multiple slices.

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

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}
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)
Reduce / ReduceEx

Reduces a slice to a value.

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

Finds minimum/maximum value in a slice.

Min(1, 2, 3, -1)    // -1
Max(1, 2, 3, -1)    // 3
MinMax(1, 2, 3, -1) // -1, 3
MinTime / MaxTime

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(2000, time.December, 2, 0, 0, 0, 0, time.UTC)
MinTime(t0, t1, t2) // t0
MinTime(t1, t2)     // t1
MaxTime(t0, t1, t2) // t2
Abs

Calculates absolute value of an integer.

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

Generates a random string.

RandString(10)                     // a random string has 10 characters (default of alphabets and digits)
RandStringEx(10, []rune("01234"))  // a random string has 10 characters (only 0-4)
Other functions

If

A convenient function works like C ternary operator.

NOTE: However, this function is deprecated as it has side effect of both expressions are evaluated and may cause the program to crash. For example: firstItem := If(len(slice) > 0, slice[0], defaultVal) will crash if slice is empty as the expression slice[0] is evaluated before the function call. Use it at your own risk.

val := If(x > 100, val1, val2) // If x > 100, val == val1, otherwise val == val2
New

Creates a new variable and return the address of it. Very helpful in unit testing.

func f(ptr *int) {}

// Normally we need to declare a var before accessing its address
val := 10
f(&val)

// With using New
f(New(10))
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"
FirstTrue

Returns the first "true" value in the given arguments if found. Values considered "true" are:

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

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.

Authors

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")
	ErrPanic           = errors.New("panic occurred")
)
View Source
var (
	StrLowerAlpha   = []rune("abcdefghijklmnopqrstuvwxyz")
	StrUpperAlpha   = []rune("ABCDEFGHIJKLMNOPQRSTUVWXYZ")
	StrDigits       = []rune("0123456789")
	StrDefaultChars = []rune("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789")
)
View Source
var (
	StructToMap   = rflutil.StructToMap
	StructToMapEx = rflutil.StructToMapEx
	ParseTag      = rflutil.ParseTag
	ParseTagOf    = rflutil.ParseTagOf
	ParseTagsOf   = rflutil.ParseTagsOf
)
View Source
var (
	// Deprecated: use ErrEmpty instead
	ErrSliceEmpty = ErrEmpty
)
View Source
var MultilineString = LinesTrimLeftSpace

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

func Any

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

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, chunkSize int) [][]T

func ChunkByPieces

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

func Compact

func Compact[T comparable](s []T) []T

func Concat

func Concat[T any](slices ...[]T) []T

Concat concatenates slices

func Contain

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

Contain tests if a slice contains an item

func ContainAll

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

ContainAll tests if a slice contains all given values

func ContainAny

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

ContainAny tests if a slice contains any given value

func ContainPred

func ContainPred[T any](a []T, pred func(t T) bool) bool

ContainPred tests if a slice contains an item by predicate

func ContainPredPtr

func ContainPredPtr[T any](a []T, pred func(t *T) bool) bool

ContainPredPtr tests if a slice contains an item by predicate

func ContainSlice

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

ContainSlice tests if a slice contains a slice

func ContentEqual

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

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

func ContentEqualPred

func ContentEqualPred[T any, K comparable](a, b []T, keyFunc func(t T) K) bool

ContentEqualPred compares 2 slices without preserving order

func ContentEqualPtr

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

ContentEqualPtr compares 2 slices of pointers without caring about order

func CountValue

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

CountValue counts number of occurrences of an item in the slice

func CountValuePred

func CountValuePred[T any](a []T, pred func(t T) bool) int

CountValuePred counts number of occurrences of an item in the slice

func Difference

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

Difference calculates the differences between two slices NOTE: this function does not return unique values

func DifferencePred

func DifferencePred[T any, K comparable](a, b []T, keyFunc func(t T) K) ([]T, []T)

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

func Equal

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

Equal compares 2 slices with preserving order

func EqualPred

func EqualPred[T any](a, b []T, equalFunc func(a, b T) bool) bool

EqualPred compares 2 slices with preserving order

func EqualPredPtr

func EqualPredPtr[T any](a, b []T, equalFunc func(a, b *T) bool) bool

EqualPredPtr compares 2 slices with preserving order

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](ps *[]T, v T) bool

FastRemove removes element value

func FastRemoveAt

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

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

func FastRemoveLastOf

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

FastRemoveLastOf removes element value

func Fill

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

Fill sets slice element values

func Filter

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

Filter filters slice elements with condition.

func FilterGT

func FilterGT[T NumberEx | StringEx](s []T, v T) []T

func FilterGTE

func FilterGTE[T NumberEx | StringEx](s []T, v T) []T

func FilterILIKE

func FilterILIKE[T StringEx](s []T, v string) []T

func FilterIN

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

func FilterLIKE

func FilterLIKE[T StringEx](s []T, v string) []T

func FilterLT

func FilterLT[T NumberEx | StringEx](s []T, v T) []T

func FilterLTE

func FilterLTE[T NumberEx | StringEx](s []T, v T) []T

func FilterNE

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

func FilterNIN

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

func FilterPtr

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

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

func FindLastPred

func FindLastPred[T any](a []T, pred func(t T) bool) (t T, found bool)

FindLastPred finds value in slice from the end by predicate

func FindLastPredPtr

func FindLastPredPtr[T any](a []T, pred func(t *T) bool) (t T, found bool)

FindLastPredPtr finds value in slice from the end by predicate

func FindPred

func FindPred[T any](a []T, pred func(t T) bool) (t T, found bool)

FindPred finds value in slice by predicate

func FindPredPtr

func FindPredPtr[T any](a []T, pred func(t *T) bool) (t T, found bool)

FindPredPtr finds value in slice by predicate

func FirstTrue

func FirstTrue[T any](a0 T, args ...T) T

FirstTrue returns the first "true" value in the given arguments if found True value is not:

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

func Flatten

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

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) []T

Flatten3 flattens 3-dimensional slices

func ForEach

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

func ForEachPtr

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

func ForEachReverse

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

func ForEachReversePtr

func ForEachReversePtr[T any](s []T, pred func(i int, t *T))

func FormatFloat

func FormatFloat[T FloatEx](v T) string

func FormatFloatEx

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

func FormatFloatGroup

func FormatFloatGroup[T FloatEx](v T) string

FormatFloatGroup format the value then group the decimal using comma

func FormatFloatGroupEx

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

FormatFloatGroupEx format the value then group the decimal using comma

func FormatInt

func FormatInt[T IntEx](v T) string

func FormatIntEx

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

func FormatIntGroup

func FormatIntGroup[T IntEx](v T) string

FormatIntGroup format the value then group the decimal using comma

func FormatUint

func FormatUint[T UIntEx](v T) string

func FormatUintEx

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

func FormatUintGroup

func FormatUintGroup[T UIntEx](v T) string

FormatUintGroup format the value then group the decimal using comma

func GetFirst

func GetFirst[T any](s []T, defaultVal T) T

func GetLast

func GetLast[T any](s []T, defaultVal T) T
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) Deprecated: this function may cause unexpected behavior upon misuses

For example: gofn.If(len(slice) > 0, slice[0], dafaultVal) will crash if slice is empty

func IndexOf

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

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

func IndexOfPred

func IndexOfPred[T any](a []T, pred func(t T) bool) int

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

func IndexOfSlice

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

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

func Intersection

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

func IntersectionPred

func IntersectionPred[T any, K comparable](a, b []T, keyFunc func(t T) K) []T

func IsSorted

func IsSorted[T NumberEx | StringEx](s []T) bool

IsSorted checks if a slice is sorted

func IsSortedDesc

func IsSortedDesc[T NumberEx | StringEx](s []T) bool

IsSortedDesc checks if a slice is sorted in descending order

func IsUnique

func IsUnique[T comparable](s []T) bool

IsUnique checks a slice for uniqueness

func IsUniquePred

func IsUniquePred[T any, U comparable](s []T, keyFunc func(t T) U) bool

IsUniquePred checks a slice for uniqueness using key function

func LastIndexOf

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

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

func LastIndexOfPred

func LastIndexOfPred[T any](a []T, pred func(t T) bool) int

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

func LastIndexOfSlice

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

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

func LinesTrim

func LinesTrim(s string, cutset string) string

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

func LinesTrimLeft

func LinesTrimLeft(s string, cutset string) string

LinesTrimLeft trim leading characters for every line in the given string

func LinesTrimLeftSpace

func LinesTrimLeftSpace(s string) string

LinesTrimLeftSpace trim leading spaces for every line in the given string

func LinesTrimRight

func LinesTrimRight(s string, cutset string) string

LinesTrimRight trim trailing characters for every line in the given string

func LinesTrimRightSpace

func LinesTrimRightSpace(s string) string

LinesTrimRightSpace trim trailing characters for every line in the given string

func LinesTrimSpace

func LinesTrimSpace(s string) string

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

func MapContainKeys

func MapContainKeys[K comparable, V any](m map[K]V, 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, 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, onlyKeys ...K) map[K]V

func MapCopyExcludeKeys added in v1.5.0

func MapCopyExcludeKeys[K comparable, V any](m map[K]V, excludedKeys ...K) map[K]V

func MapDifferenceKeys

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

func MapEqual

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

MapEqual compares contents of 2 map

func MapEqualPred

func MapEqualPred[K comparable, V any](m1, m2 map[K]V, equalFunc func(v1, v2 V) bool) bool

MapEqualPred compares contents of 2 map

func MapGet

func MapGet[K comparable, V any](m map[K]V, 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](m1 map[K]V, ms ...map[K]V) []K

func MapKeys

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

MapKeys gets map keys as slice

func MapPop

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

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

func MapSetDefault

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

func MapSlice

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

MapSlice transforms a slice to another with map function

func MapSliceEx

func MapSliceEx[T any, U any](s []T, mapFunc func(b 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, mapFunc func(b 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, mapFunc func(b T) (K, V, error)) (map[K]V, error)

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

func MapUnionKeys

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

func MapUpdate

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

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](m1, m2 map[K]V) map[K]V

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](m1, m2 map[K]V) map[K]V

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 NumberEx | ~string](v1 T, s ...T) T

Max find the maximum value in the list

func MaxIn

func MaxIn[T NumberEx | ~string](s []T) (T, error)

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

func MaxInPred

func MaxInPred[T any](s []T, lessFunc func(a, b T) bool) (T, error)

MaxInPred 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 NumberEx | ~string](v1 T, s ...T) T

Min find the minimum value in the list

func MinIn

func MinIn[T NumberEx | ~string](s []T) (T, error)

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

func MinInPred

func MinInPred[T any](s []T, lessFunc func(a, b T) bool) (T, error)

MinInPred find the minimum value in the list

func MinMax

func MinMax[T NumberEx | ~string](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 New

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

New returns pointer to the address of the input Helpful for unit testing when create a struct that has field requires pointer type

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 FloatEx](s string) (T, error)

func ParseFloatDef

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

func ParseFloatUngroup

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

ParseFloatUngroup omit all grouping commas then parse the string value

func ParseInt

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

func ParseIntDef

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

func ParseIntEx

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

func ParseIntUngroup

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

ParseIntUngroup omit all grouping commas then parse the string value

func ParseUint

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

func ParseUintDef

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

func ParseUintEx

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

func ParseUintUngroup

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

ParseUintUngroup omit all grouping commas then parse the string value

func Product

func Product[T IntEx | UIntEx | FloatEx](s ...T) T

func ProductAs

func ProductAs[U, T IntEx | UIntEx | FloatEx](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 RandString

func RandString(n int) string

RandString generates a random string

func RandStringEx

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

RandStringEx generates a random string

func Reduce

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

func ReduceEx

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

func Remove

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

Remove removes element value

func RemoveAll

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

RemoveAll removes all occurrences of value

func RemoveAt

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

RemoveAt removes element at the specified index

func RemoveLastOf

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

RemoveLastOf removes element value

func Replace

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

Replace replaces a value in slice with another value

func ReplaceAll

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

ReplaceAll replaces a value in slice with another value

func Reverse

func Reverse[T any](s []T) []T

Reverse func Reverse[S ~[]E, E any](s S) {

func ReverseCopy

func ReverseCopy[T any](s []T) []T

func SliceByRange added in v1.6.0

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

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

func Sort

func Sort[T NumberEx | StringEx](s []T) []T

Sort sorts slice values

func SortDesc

func SortDesc[T NumberEx | StringEx](s []T) []T

SortDesc sorts slice values in descending order

func SortEx

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

SortEx sorts slice values

func SortStable

func SortStable[T NumberEx | StringEx](s []T) []T

SortStable sorts slice values

func SortStableDesc

func SortStableDesc[T NumberEx | StringEx](s []T) []T

SortStableDesc sorts slice values in descending order

func SortStableEx

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

SortStableEx sorts slice values

func StringJoin

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

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

func StringJoinEx

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

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

func StringJoinPred

func StringJoinPred[T any](s []T, sep string, fmtFunc func(v T) string) string

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

func SubSlice added in v1.6.0

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

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 IntEx | UIntEx | FloatEx](s ...T) T

func SumAs

func SumAs[U, T IntEx | UIntEx | FloatEx](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 ToIntfSlice

func ToIntfSlice[T any](s []T) []any

ToIntfSlice convert a slice to a slice of interface

func ToNumberSlice

func ToNumberSlice[U, T NumberEx](slice []T) []U

ToNumberSlice converts int-approximate slice to int slice

func ToSet

func ToSet[T comparable](s []T) []T

func ToSetPred

func ToSetPred[T any, K comparable](s []T, keyFunc func(t T) K) []T

func ToSlice

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

ToSlice returns a slice for individual input arguments

func ToStringSlice

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

ToStringSlice converts str-approximate slice to string slice

func Union

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

func UnionPred

func UnionPred[T any, K comparable](a, b []T, keyFunc func(t T) K) []T

Types

type Float

type Float interface {
	float32 | float64
}

type FloatEx

type FloatEx interface {
	~float32 | ~float64
}

type Int

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

type IntEx

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

type Number

type Number interface {
	Int | UInt | Float
}

type NumberEx

type NumberEx interface {
	IntEx | UIntEx | FloatEx
}

type StringEx

type StringEx interface {
	~string
}

type Tuple2

type Tuple2[T any, U any] struct {
	Elem1 T
	Elem2 U
}

func MapEntries

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

MapEntries returns a slice of map entries as Tuple2 type

func Zip

func Zip[T any, U any](slice1 []T, slice2 []U) []*Tuple2[T, U]

type Tuple3

type Tuple3[T any, U any, V any] struct {
	Elem1 T
	Elem2 U
	Elem3 V
}

func Zip3

func Zip3[T any, U any, V any](slice1 []T, slice2 []U, slice3 []V) []*Tuple3[T, U, V]

type UInt

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

type UIntEx

type UIntEx interface {
	~uint | ~uint8 | ~uint16 | ~uint32 | ~uint64
}

Jump to

Keyboard shortcuts

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