slice

package
v2.3.3 Latest Latest
Warning

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

Go to latest
Published: Oct 9, 2024 License: MIT Imports: 10 Imported by: 69

Documentation

Overview

Package slice implements some functions to manipulate slice.

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func AppendIfAbsent added in v2.1.4

func AppendIfAbsent[T comparable](slice []T, item T) []T

AppendIfAbsent only absent append the item. Play: https://go.dev/play/p/KcC1QXQ-RkL

Example
result1 := AppendIfAbsent([]string{"a", "b"}, "b")
result2 := AppendIfAbsent([]string{"a", "b"}, "c")

fmt.Println(result1)
fmt.Println(result2)
Output:

[a b]
[a b c]

func Break added in v2.3.1

func Break[T any](values []T, predicate func(T) bool) ([]T, []T)

Breaks a list into two parts at the point where the predicate for the first time is true. Play: https://go.dev/play/p/yLYcBTyeQIz

Example
nums := []int{1, 2, 3, 4, 5}
even := func(n int) bool { return n%2 == 0 }

resultEven, resultAfterFirstEven := Break(nums, even)
fmt.Println(resultEven)
fmt.Println(resultAfterFirstEven)
Output:

[1]
[2 3 4 5]

func Chunk

func Chunk[T any](slice []T, size int) [][]T

Chunk creates a slice of elements split into groups the length of size. Play: https://go.dev/play/p/b4Pou5j2L_C

Example
arr := []string{"a", "b", "c", "d", "e"}

result1 := Chunk(arr, 1)
result2 := Chunk(arr, 2)
result3 := Chunk(arr, 3)
result4 := Chunk(arr, 4)
result5 := Chunk(arr, 5)

fmt.Println(result1)
fmt.Println(result2)
fmt.Println(result3)
fmt.Println(result4)
fmt.Println(result5)
Output:

[[a] [b] [c] [d] [e]]
[[a b] [c d] [e]]
[[a b c] [d e]]
[[a b c d] [e]]
[[a b c d e]]

func Compact

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

Compact creates a slice with all falsey values removed. The values false, nil, 0, and "" are falsey. Play: https://go.dev/play/p/pO5AnxEr3TK

Example
result1 := Compact([]int{0})
result2 := Compact([]int{0, 1, 2, 3})
result3 := Compact([]string{"", "a", "b", "0"})
result4 := Compact([]bool{false, true, true})

fmt.Println(result1)
fmt.Println(result2)
fmt.Println(result3)
fmt.Println(result4)
Output:

[]
[1 2 3]
[a b 0]
[true true]

func Concat

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

Concat creates a new slice concatenating slice with any additional slices. Play: https://go.dev/play/p/gPt-q7zr5mk

Example
result1 := Concat([]int{1, 2}, []int{3, 4})
result2 := Concat([]string{"a", "b"}, []string{"c"}, []string{"d"})

fmt.Println(result1)
fmt.Println(result2)
Output:

[1 2 3 4]
[a b c d]

func Contain

func Contain[T comparable](slice []T, target T) bool

Contain check if the target value is in the slice or not. Play: https://go.dev/play/p/_454yEHcNjf

Example
result1 := Contain([]string{"a", "b", "c"}, "a")
result2 := Contain([]int{1, 2, 3}, 4)

fmt.Println(result1)
fmt.Println(result2)
Output:

true
false

func ContainBy added in v2.1.16

func ContainBy[T any](slice []T, predicate func(item T) bool) bool

ContainBy returns true if predicate function return true. Play: https://go.dev/play/p/49tkHfX4GNc

Example
type foo struct {
	A string
	B int
}

array1 := []foo{{A: "1", B: 1}, {A: "2", B: 2}}
result1 := ContainBy(array1, func(f foo) bool { return f.A == "1" && f.B == 1 })
result2 := ContainBy(array1, func(f foo) bool { return f.A == "2" && f.B == 1 })

array2 := []string{"a", "b", "c"}
result3 := ContainBy(array2, func(t string) bool { return t == "a" })
result4 := ContainBy(array2, func(t string) bool { return t == "d" })

fmt.Println(result1)
fmt.Println(result2)
fmt.Println(result3)
fmt.Println(result4)
Output:

true
false
true
false

func ContainSubSlice

func ContainSubSlice[T comparable](slice, subSlice []T) bool

ContainSubSlice check if the slice contain a given subslice or not. Play: https://go.dev/play/p/bcuQ3UT6Sev

Example
result1 := ContainSubSlice([]string{"a", "b", "c"}, []string{"a", "b"})
result2 := ContainSubSlice([]string{"a", "b", "c"}, []string{"a", "d"})

fmt.Println(result1)
fmt.Println(result2)
Output:

true
false

func Count

func Count[T comparable](slice []T, item T) int

Count returns the number of occurrences of the given item in the slice. Play: https://go.dev/play/p/Mj4oiEnQvRJ

Example
nums := []int{1, 2, 3, 3, 4}

result1 := Count(nums, 1)
result2 := Count(nums, 3)

fmt.Println(result1)
fmt.Println(result2)
Output:

1
2

func CountBy added in v2.1.11

func CountBy[T any](slice []T, predicate func(index int, item T) bool) int

CountBy iterates over elements of slice with predicate function, returns the number of all matched elements. Play: https://go.dev/play/p/tHOccTMDZCC

Example
nums := []int{1, 2, 3, 4, 5}

isEven := func(i, num int) bool {
	return num%2 == 0
}

result := CountBy(nums, isEven)

fmt.Println(result)
Output:

2

func DeleteAt

func DeleteAt[T any](slice []T, index int) []T

DeleteAt delete the element of slice at index. Play: https://go.dev/play/p/800B1dPBYyd

Example
chars := []string{"a", "b", "c", "d", "e"}

result1 := DeleteAt(chars, 0)
result2 := DeleteAt(chars, 4)
result3 := DeleteAt(chars, 5)
result4 := DeleteAt(chars, 6)

fmt.Println(result1)
fmt.Println(result2)
fmt.Println(result3)
fmt.Println(result4)
Output:

[b c d e]
[a b c d]
[a b c d]
[a b c d]

func DeleteRange added in v2.2.9

func DeleteRange[T any](slice []T, start, end int) []T

DeleteRange delete the element of slice from start index to end index(exclude). Play: https://go.dev/play/p/945HwiNrnle

Example
chars := []string{"a", "b", "c", "d", "e"}

result1 := DeleteRange(chars, 0, 0)
result2 := DeleteRange(chars, 0, 1)
result3 := DeleteRange(chars, 0, 3)
result4 := DeleteRange(chars, 0, 4)
result5 := DeleteRange(chars, 0, 5)

fmt.Println(result1)
fmt.Println(result2)
fmt.Println(result3)
fmt.Println(result4)
fmt.Println(result5)
Output:

[a b c d e]
[b c d e]
[d e]
[e]
[]

func Difference

func Difference[T comparable](slice, comparedSlice []T) []T

Difference creates a slice of whose element in slice but not in comparedSlice. Play: https://go.dev/play/p/VXvadzLzhDa

Example
slice1 := []int{1, 2, 3, 4, 5}
slice2 := []int{4, 5, 6}

result := Difference(slice1, slice2)

fmt.Println(result)
Output:

[1 2 3]

func DifferenceBy

func DifferenceBy[T comparable](slice []T, comparedSlice []T, iteratee func(index int, item T) T) []T

DifferenceBy it accepts iteratee which is invoked for each element of slice and values to generate the criterion by which they're compared. like lodash.js differenceBy: https://lodash.com/docs/4.17.15#differenceBy. Play: https://go.dev/play/p/DiivgwM5OnC

Example
slice1 := []int{1, 2, 3, 4, 5} //after add one: 2 3 4 5 6
slice2 := []int{3, 4, 5}       //after add one: 4 5 6

addOne := func(i int, v int) int {
	return v + 1
}

result := DifferenceBy(slice1, slice2, addOne)

fmt.Println(result)
Output:

[1 2]

func DifferenceWith

func DifferenceWith[T any](slice []T, comparedSlice []T, comparator func(item1, item2 T) bool) []T

DifferenceWith accepts comparator which is invoked to compare elements of slice to values. The order and references of result values are determined by the first slice. The comparator is invoked with two arguments: (arrVal, othVal). Play: https://go.dev/play/p/v2U2deugKuV

Example
slice1 := []int{1, 2, 3, 4, 5}
slice2 := []int{4, 5, 6, 7, 8}

isDouble := func(v1, v2 int) bool {
	return v2 == 2*v1
}

result := DifferenceWith(slice1, slice2, isDouble)

fmt.Println(result)
Output:

[1 5]

func Drop

func Drop[T any](slice []T, n int) []T

Drop drop n elements from the start of a slice. Play: https://go.dev/play/p/jnPO2yQsT8H

Example
result1 := Drop([]string{"a", "b", "c"}, 0)
result2 := Drop([]string{"a", "b", "c"}, 1)
result3 := Drop([]string{"a", "b", "c"}, -1)
result4 := Drop([]string{"a", "b", "c"}, 4)

fmt.Println(result1)
fmt.Println(result2)
fmt.Println(result3)
fmt.Println(result4)
Output:

[a b c]
[b c]
[a b c]
[]

func DropRight added in v2.1.15

func DropRight[T any](slice []T, n int) []T

DropRight drop n elements from the end of a slice. Play: https://go.dev/play/p/8bcXvywZezG

Example
result1 := DropRight([]string{"a", "b", "c"}, 0)
result2 := DropRight([]string{"a", "b", "c"}, 1)
result3 := DropRight([]string{"a", "b", "c"}, -1)
result4 := DropRight([]string{"a", "b", "c"}, 4)

fmt.Println(result1)
fmt.Println(result2)
fmt.Println(result3)
fmt.Println(result4)
Output:

[a b c]
[a b]
[a b c]
[]

func DropRightWhile added in v2.1.15

func DropRightWhile[T any](slice []T, predicate func(item T) bool) []T

DropRightWhile drop n elements from the end of a slice while predicate function returns true. Play: https://go.dev/play/p/6wyK3zMY56e

Example
numbers := []int{1, 2, 3, 4, 5}

result1 := DropRightWhile(numbers, func(n int) bool {
	return n != 2
})
result2 := DropRightWhile(numbers, func(n int) bool {
	return true
})
result3 := DropRightWhile(numbers, func(n int) bool {
	return n == 0
})

fmt.Println(result1)
fmt.Println(result2)
fmt.Println(result3)
Output:

[1 2]
[]
[1 2 3 4 5]

func DropWhile added in v2.1.15

func DropWhile[T any](slice []T, predicate func(item T) bool) []T

DropWhile drop n elements from the start of a slice while predicate function returns true. Play: https://go.dev/play/p/4rt252UV_qs

Example
numbers := []int{1, 2, 3, 4, 5}

result1 := DropWhile(numbers, func(n int) bool {
	return n != 2
})
result2 := DropWhile(numbers, func(n int) bool {
	return true
})
result3 := DropWhile(numbers, func(n int) bool {
	return n == 0
})

fmt.Println(result1)
fmt.Println(result2)
fmt.Println(result3)
Output:

[2 3 4 5]
[]
[1 2 3 4 5]

func Equal added in v2.0.9

func Equal[T comparable](slice1, slice2 []T) bool

Equal checks if two slices are equal: the same length and all elements' order and value are equal. Play: https://go.dev/play/p/WcRQJ37ifPa

Example
slice1 := []int{1, 2, 3}
slice2 := []int{1, 2, 3}
slice3 := []int{1, 3, 2}

result1 := Equal(slice1, slice2)
result2 := Equal(slice1, slice3)

fmt.Println(result1)
fmt.Println(result2)
Output:

true
false

func EqualWith added in v2.0.9

func EqualWith[T, U any](slice1 []T, slice2 []U, comparator func(T, U) bool) bool

EqualWith checks if two slices are equal with comparator func. Play: https://go.dev/play/p/b9iygtgsHI1

Example
slice1 := []int{1, 2, 3}
slice2 := []int{2, 4, 6}

isDouble := func(a, b int) bool {
	return b == a*2
}

result := EqualWith(slice1, slice2, isDouble)

fmt.Println(result)
Output:

true

func Every

func Every[T any](slice []T, predicate func(index int, item T) bool) bool

Every return true if all of the values in the slice pass the predicate function. Play: https://go.dev/play/p/R8U6Sl-j8cD

Example
nums := []int{1, 2, 3, 5}

isEven := func(i, num int) bool {
	return num%2 == 0
}

result := Every(nums, isEven)

fmt.Println(result)
Output:

false

func Filter

func Filter[T any](slice []T, predicate func(index int, item T) bool) []T

Filter iterates over elements of slice, returning an slice of all elements pass the predicate function. Play: https://go.dev/play/p/SdPna-7qK4T

Example
nums := []int{1, 2, 3, 4, 5}

isEven := func(i, num int) bool {
	return num%2 == 0
}

result := Filter(nums, isEven)

fmt.Println(result)
Output:

[2 4]

func FilterConcurrent added in v2.3.3

func FilterConcurrent[T any](slice []T, predicate func(index int, item T) bool, numThreads int) []T

FilterConcurrent applies the provided filter function `predicate` to each element of the input slice concurrently. Play: todo

Example
nums := []int{1, 2, 3, 4, 5}

isEven := func(i, num int) bool {
	return num%2 == 0
}

result := FilterConcurrent(nums, isEven, 2)

fmt.Println(result)
Output:

[2 4]

func FilterMap added in v2.1.16

func FilterMap[T any, U any](slice []T, iteratee func(index int, item T) (U, bool)) []U

FilterMap returns a slice which apply both filtering and mapping to the given slice. iteratee callback function should returntwo values: 1, mapping result. 2, whether the result element should be included or not Play: https://go.dev/play/p/J94SZ_9MiIe

Example
nums := []int{1, 2, 3, 4, 5}

getEvenNumStr := func(i, num int) (string, bool) {
	if num%2 == 0 {
		return strconv.FormatInt(int64(num), 10), true
	}
	return "", false
}

result := FilterMap(nums, getEvenNumStr)

fmt.Printf("%#v", result)
Output:

[]string{"2", "4"}

func Find

func Find[T any](slice []T, predicate func(index int, item T) bool) (*T, bool)

Find iterates over elements of slice, returning the first one that passes a truth test on predicate function. If return T is nil then no items matched the predicate func. Play: https://go.dev/play/p/CBKeBoHVLgq Deprecated

Example
nums := []int{1, 2, 3, 4, 5}

isEven := func(i, num int) bool {
	return num%2 == 0
}

result, ok := Find(nums, isEven)

fmt.Println(*result)
fmt.Println(ok)
Output:

2
true

func FindBy added in v2.1.20

func FindBy[T any](slice []T, predicate func(index int, item T) bool) (v T, ok bool)

FindBy iterates over elements of slice, returning the first one that passes a truth test on predicate function. If return T is nil or zero value then no items matched the predicate func. In contrast to Find or FindLast, its return value no longer requires dereferencing Play: https://go.dev/play/p/n1lysBYl-GB

Example
nums := []int{1, 2, 3, 4, 5}

isEven := func(i, num int) bool {
	return num%2 == 0
}

result, ok := FindBy(nums, isEven)

fmt.Println(result)
fmt.Println(ok)
Output:

2
true

func FindLast

func FindLast[T any](slice []T, predicate func(index int, item T) bool) (*T, bool)

FindLast iterates over elements of slice from end to begin, return the first one that passes a truth test on predicate function. If return T is nil then no items matched the predicate func. Play: https://go.dev/play/p/FFDPV_j7URd Deprecated

Example
nums := []int{1, 2, 3, 4, 5}

isEven := func(i, num int) bool {
	return num%2 == 0
}

result, ok := FindLast(nums, isEven)

fmt.Println(*result)
fmt.Println(ok)
Output:

4
true

func FindLastBy added in v2.1.20

func FindLastBy[T any](slice []T, predicate func(index int, item T) bool) (v T, ok bool)

FindLastBy iterates over elements of slice, returning the last one that passes a truth test on predicate function. If return T is nil or zero value then no items matched the predicate func. In contrast to Find or FindLast, its return value no longer requires dereferencing Play: https://go.dev/play/p/8iqomzyCl_s

Example
nums := []int{1, 2, 3, 4, 5}

isEven := func(i, num int) bool {
	return num%2 == 0
}

result, ok := FindLastBy(nums, isEven)

fmt.Println(result)
fmt.Println(ok)
Output:

4
true

func FlatMap added in v2.1.16

func FlatMap[T any, U any](slice []T, iteratee func(index int, item T) []U) []U

FlatMap manipulates a slice and transforms and flattens it to a slice of another type. Play: https://go.dev/play/p/_QARWlWs1N_F

Example
nums := []int{1, 2, 3, 4}

result := FlatMap(nums, func(i int, num int) []string {
	s := "hi-" + strconv.FormatInt(int64(num), 10)
	return []string{s}
})

fmt.Printf("%#v", result)
Output:

[]string{"hi-1", "hi-2", "hi-3", "hi-4"}

func Flatten added in v2.1.3

func Flatten(slice any) any

Flatten flattens slice with one level. Play: https://go.dev/play/p/hYa3cBEevtm

Example
arrs := [][][]string{{{"a", "b"}}, {{"c", "d"}}}

result := Flatten(arrs)

fmt.Println(result)
Output:

[[a b] [c d]]

func FlattenDeep

func FlattenDeep(slice any) any

FlattenDeep flattens slice recursive. Play: https://go.dev/play/p/yjYNHPyCFaF

Example
arrs := [][][]string{{{"a", "b"}}, {{"c", "d"}}}

result := FlattenDeep(arrs)

fmt.Println(result)
Output:

[a b c d]

func ForEach

func ForEach[T any](slice []T, iteratee func(index int, item T))

ForEach iterates over elements of slice and invokes function for each element. Play: https://go.dev/play/p/DrPaa4YsHRF

Example
nums := []int{1, 2, 3}

var result []int
addOne := func(_ int, v int) {
	result = append(result, v+1)
}

ForEach(nums, addOne)

fmt.Println(result)
Output:

[2 3 4]

func ForEachConcurrent added in v2.3.3

func ForEachConcurrent[T any](slice []T, iteratee func(index int, item T), numThreads int)

ForEachConcurrent applies the iteratee function to each item in the slice concurrently. Play: todo

Example
nums := []int{1, 2, 3, 4, 5, 6, 7, 8}

result := make([]int, len(nums))

addOne := func(index int, value int) {
	result[index] = value + 1
}

ForEachConcurrent(nums, addOne, 4)

fmt.Println(result)
Output:

[2 3 4 5 6 7 8 9]

func ForEachWithBreak added in v2.1.17

func ForEachWithBreak[T any](slice []T, iteratee func(index int, item T) bool)

ForEachWithBreak iterates over elements of slice and invokes function for each element, when iteratee return false, will break the for each loop. Play: https://go.dev/play/p/qScs39f3D9W

Example
numbers := []int{1, 2, 3, 4, 5}

var sum int

ForEachWithBreak(numbers, func(_, n int) bool {
	if n > 3 {
		return false
	}
	sum += n
	return true
})

fmt.Println(sum)
Output:

6

func Frequency added in v2.3.3

func Frequency[T comparable](slice []T) map[T]int

Frequency counts the frequency of each element in the slice. Play: todo

Example
strs := []string{"a", "b", "b", "c", "c", "c"}
result := Frequency(strs)

fmt.Println(result)
Output:

map[a:1 b:2 c:3]

func GroupBy

func GroupBy[T any](slice []T, groupFn func(index int, item T) bool) ([]T, []T)

GroupBy iterate over elements of the slice, each element will be group by criteria, returns two slices. Play: https://go.dev/play/p/QVkPxzPR0iA

Example
nums := []int{1, 2, 3, 4, 5}

isEven := func(i, num int) bool {
	return num%2 == 0
}

even, odd := GroupBy(nums, isEven)

fmt.Println(even)
fmt.Println(odd)
Output:

[2 4]
[1 3 5]

func GroupWith added in v2.0.1

func GroupWith[T any, U comparable](slice []T, iteratee func(item T) U) map[U][]T

GroupWith return a map composed of keys generated from the resultults of running each element of slice thru iteratee. Play: https://go.dev/play/p/ApCvMNTLO8a

Example
nums := []float64{6.1, 4.2, 6.3}

floor := func(num float64) float64 {
	return math.Floor(num)
}

result := GroupWith(nums, floor) //map[float64][]float64

fmt.Println(result)
Output:

map[4:[4.2] 6:[6.1 6.3]]

func IndexOf added in v2.0.7

func IndexOf[T comparable](arr []T, val T) int

IndexOf returns the index at which the first occurrence of an item is found in a slice or return -1 if the item cannot be found. Play: https://go.dev/play/p/MRN1f0FpABb

Example
strs := []string{"a", "a", "b", "c"}

result1 := IndexOf(strs, "a")
result2 := IndexOf(strs, "d")

fmt.Println(result1)
fmt.Println(result2)
Output:

0
-1

func InsertAt

func InsertAt[T any](slice []T, index int, value any) []T

InsertAt insert the value or other slice into slice at index. Play: https://go.dev/play/p/hMLNxPEGJVE

Example
result1 := InsertAt([]string{"a", "b", "c"}, 0, "1")
result2 := InsertAt([]string{"a", "b", "c"}, 1, "1")
result3 := InsertAt([]string{"a", "b", "c"}, 2, "1")
result4 := InsertAt([]string{"a", "b", "c"}, 3, "1")
result5 := InsertAt([]string{"a", "b", "c"}, 0, []string{"1", "2", "3"})

fmt.Println(result1)
fmt.Println(result2)
fmt.Println(result3)
fmt.Println(result4)
fmt.Println(result5)
Output:

[1 a b c]
[a 1 b c]
[a b 1 c]
[a b c 1]
[1 2 3 a b c]

func IntSlice

func IntSlice(slice any) []int

IntSlice convert param to slice of int. This function is deprecated, use generics feature of go1.18+ for replacement. Play: https://go.dev/play/p/UQDj-on9TGN

Example
nums := []interface{}{1, 2, 3}

result := IntSlice(nums) //[]int{1, 2, 3}
fmt.Println(result)
Output:

[1 2 3]

func InterfaceSlice

func InterfaceSlice(slice any) []any

InterfaceSlice convert param to slice of interface. This function is deprecated, use generics feature of go1.18+ for replacement. Play: https://go.dev/play/p/FdQXF0Vvqs-

Example
strs := []string{"a", "b", "c"}

result := InterfaceSlice(strs) //[]interface{}{"a", "b", "c"}
fmt.Println(result)
Output:

[a b c]

func Intersection

func Intersection[T comparable](slices ...[]T) []T

Intersection creates a slice of unique elements that included by all slices. Play: https://go.dev/play/p/anJXfB5wq_t

Example
nums1 := []int{1, 2, 3}
nums2 := []int{2, 3, 4}

result := Intersection(nums1, nums2)

fmt.Println(result)
Output:

[2 3]

func IsAscending added in v2.1.15

func IsAscending[T constraints.Ordered](slice []T) bool

IsAscending checks if a slice is ascending order. Play: https://go.dev/play/p/9CtsFjet4SH

Example
result1 := IsAscending([]int{1, 2, 3, 4, 5})
result2 := IsAscending([]int{5, 4, 3, 2, 1})
result3 := IsAscending([]int{2, 1, 3, 4, 5})

fmt.Println(result1)
fmt.Println(result2)
fmt.Println(result3)
Output:

true
false
false

func IsDescending added in v2.1.15

func IsDescending[T constraints.Ordered](slice []T) bool

IsDescending checks if a slice is descending order. Play: https://go.dev/play/p/U_LljFXma14

Example
result1 := IsDescending([]int{5, 4, 3, 2, 1})
result2 := IsDescending([]int{1, 2, 3, 4, 5})
result3 := IsDescending([]int{2, 1, 3, 4, 5})

fmt.Println(result1)
fmt.Println(result2)
fmt.Println(result3)
Output:

true
false
false

func IsSorted added in v2.1.15

func IsSorted[T constraints.Ordered](slice []T) bool

IsSorted checks if a slice is sorted(ascending or descending). Play: https://go.dev/play/p/nCE8wPLwSA-

Example
result1 := IsSorted([]int{1, 2, 3, 4, 5})
result2 := IsSorted([]int{5, 4, 3, 2, 1})
result3 := IsSorted([]int{2, 1, 3, 4, 5})

fmt.Println(result1)
fmt.Println(result2)
fmt.Println(result3)
Output:

true
true
false

func IsSortedByKey added in v2.1.15

func IsSortedByKey[T any, K constraints.Ordered](slice []T, iteratee func(item T) K) bool

IsSortedByKey checks if a slice is sorted by iteratee function. Play: https://go.dev/play/p/tUoGB7DOHI4

Example
result1 := IsSortedByKey([]string{"a", "ab", "abc"}, func(s string) int {
	return len(s)
})
result2 := IsSortedByKey([]string{"abc", "ab", "a"}, func(s string) int {
	return len(s)
})
result3 := IsSortedByKey([]string{"abc", "a", "ab"}, func(s string) int {
	return len(s)
})

fmt.Println(result1)
fmt.Println(result2)
fmt.Println(result3)
Output:

true
true
false

func Join added in v2.2.4

func Join[T any](slice []T, separator string) string

Join the slice item with specify separator. Play: https://go.dev/play/p/huKzqwNDD7V

Example
nums := []int{1, 2, 3, 4, 5}

result1 := Join(nums, ",")
result2 := Join(nums, "-")

fmt.Println(result1)
fmt.Println(result2)
Output:

1,2,3,4,5
1-2-3-4-5

func KeyBy added in v2.1.9

func KeyBy[T any, U comparable](slice []T, iteratee func(item T) U) map[U]T

KeyBy converts a slice to a map based on a callback function. Play: https://go.dev/play/p/uXod2LWD1Kg

Example
result := KeyBy([]string{"a", "ab", "abc"}, func(str string) int {
	return len(str)
})

fmt.Println(result)
Output:

map[1:a 2:ab 3:abc]

func LastIndexOf added in v2.0.7

func LastIndexOf[T comparable](slice []T, item T) int

LastIndexOf returns the index at which the last occurrence of the item is found in a slice or return -1 if the then cannot be found. Play: https://go.dev/play/p/DokM4cf1IKH

Example
strs := []string{"a", "a", "b", "c"}

result1 := LastIndexOf(strs, "a")
result2 := LastIndexOf(strs, "d")

fmt.Println(result1)
fmt.Println(result2)
Output:

1
-1

func LeftPadding added in v2.3.1

func LeftPadding[T any](slice []T, paddingValue T, paddingLength int) []T

LeftPadding adds padding to the left begin of a slice. Play: https://go.dev/play/p/jlQVoelLl2k

Example
nums := []int{1, 2, 3, 4, 5}
padded := LeftPadding(nums, 0, 3)
fmt.Println(padded)
Output:

[0 0 0 1 2 3 4 5]

func Map

func Map[T any, U any](slice []T, iteratee func(index int, item T) U) []U

Map creates an slice of values by running each element of slice thru iteratee function. Play: https://go.dev/play/p/biaTefqPquw

Example
nums := []int{1, 2, 3}

addOne := func(_ int, v int) int {
	return v + 1
}

result := Map(nums, addOne)

fmt.Println(result)
Output:

[2 3 4]

func MapConcurrent added in v2.3.3

func MapConcurrent[T any, U any](slice []T, iteratee func(index int, item T) U, numThreads int) []U

MapConcurrent applies the iteratee function to each item in the slice concurrently. Play: todo

Example
nums := []int{1, 2, 3, 4, 5, 6}
result := MapConcurrent(nums, func(_, n int) int { return n * n }, 4)

fmt.Println(result)
Output:

[1 4 9 16 25 36]

func Merge deprecated added in v2.1.11

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

Deprecated: Please use Concat() function instead. Merge all given slices into one slice. Play: https://go.dev/play/p/lbjFp784r9N

Example
nums1 := []int{1, 2, 3}
nums2 := []int{3, 4}

result := Merge(nums1, nums2)

fmt.Println(result)
Output:

[1 2 3 3 4]

func None

func None[T any](slice []T, predicate func(index int, item T) bool) bool

None return true if all the values in the slice mismatch the criteria. Play: https://go.dev/play/p/KimdalUlC-T

Example
nums := []int{1, 3, 5}

isEven := func(i, num int) bool {
	return num%2 == 0
}

result := None(nums, isEven)

fmt.Println(result)
Output:

true

func Partition added in v2.2.6

func Partition[T any](slice []T, predicates ...func(item T) bool) [][]T

Partition all slice elements with the evaluation of the given predicate functions. Play: https://go.dev/play/p/lkQ3Ri2NQhV

Example
nums := []int{1, 2, 3, 4, 5}

result1 := Partition(nums)
result2 := Partition(nums, func(n int) bool { return n%2 == 0 })
result3 := Partition(nums, func(n int) bool { return n == 1 || n == 2 }, func(n int) bool { return n == 2 || n == 3 || n == 4 })

fmt.Println(result1)
fmt.Println(result2)
fmt.Println(result3)
Output:

[[1 2 3 4 5]]
[[2 4] [1 3 5]]
[[1 2] [3 4] [5]]

func Random added in v2.2.8

func Random[T any](slice []T) (val T, idx int)

Random get a random item of slice, return idx=-1 when slice is empty Play: https://go.dev/play/p/UzpGQptWppw

Example
nums := []int{1, 2, 3, 4, 5}

val, idx := Random(nums)
if idx >= 0 && idx < len(nums) && Contain(nums, val) {
	fmt.Println("okk")
}
Output:

okk

func Reduce

func Reduce[T any](slice []T, iteratee func(index int, item1, item2 T) T, initial T) T

Reduce creates an slice of values by running each element of slice thru iteratee function. Play: https://go.dev/play/p/_RfXJJWIsIm

Example
nums := []int{1, 2, 3}

sum := func(_ int, v1, v2 int) int {
	return v1 + v2
}

result := Reduce(nums, sum, 0)

fmt.Println(result)
Output:

6

func ReduceBy added in v2.1.19

func ReduceBy[T any, U any](slice []T, initial U, reducer func(index int, item T, agg U) U) U

ReduceBy produces a value from slice by accumulating the result of each element as passed through the reducer function. Play: https://go.dev/play/p/YKDpLi7gtee

Example
result1 := ReduceBy([]int{1, 2, 3, 4}, 0, func(_ int, item int, agg int) int {
	return agg + item
})

result2 := ReduceBy([]int{1, 2, 3, 4}, "", func(_ int, item int, agg string) string {
	return agg + fmt.Sprintf("%v", item)
})

fmt.Println(result1)
fmt.Println(result2)
Output:

10
1234

func ReduceConcurrent added in v2.3.3

func ReduceConcurrent[T any](slice []T, initial T, reducer func(index int, item T, agg T) T, numThreads int) T

ReduceConcurrent reduces the slice to a single value by applying the reducer function to each item in the slice concurrently. Play: todo

Example
nums := []int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
result := ReduceConcurrent(nums, 0, func(_ int, item, agg int) int {
	return agg + item
}, 1)

fmt.Println(result)
Output:

55

func ReduceRight added in v2.1.19

func ReduceRight[T any, U any](slice []T, initial U, reducer func(index int, item T, agg U) U) U

ReduceRight is like ReduceBy, but it iterates over elements of slice from right to left. Play: https://go.dev/play/p/qT9dZC03A1K

Example
result := ReduceRight([]int{1, 2, 3, 4}, "", func(_ int, item int, agg string) string {
	return agg + fmt.Sprintf("%v", item)
})

fmt.Println(result)
Output:

4321

func Repeat added in v2.1.11

func Repeat[T any](item T, n int) []T

Repeat creates a slice with length n whose elements are param `item`. Play: https://go.dev/play/p/1CbOmtgILUU

Example
result := Repeat("a", 3)

fmt.Println(result)
Output:

[a a a]

func Replace added in v2.1.8

func Replace[T comparable](slice []T, old T, new T, n int) []T

Replace returns a copy of the slice with the first n non-overlapping instances of old replaced by new. Play: https://go.dev/play/p/P5mZp7IhOFo

Example
strs := []string{"a", "b", "c", "a"}

result1 := Replace(strs, "a", "x", 0)
result2 := Replace(strs, "a", "x", 1)
result3 := Replace(strs, "a", "x", 2)
result4 := Replace(strs, "a", "x", 3)
result5 := Replace(strs, "a", "x", -1)

fmt.Println(result1)
fmt.Println(result2)
fmt.Println(result3)
fmt.Println(result4)
fmt.Println(result5)
Output:

[a b c a]
[x b c a]
[x b c x]
[x b c x]
[x b c x]

func ReplaceAll added in v2.1.8

func ReplaceAll[T comparable](slice []T, old T, new T) []T

ReplaceAll returns a copy of the slice with all non-overlapping instances of old replaced by new. Play: https://go.dev/play/p/CzqXMsuYUrx

Example
result := ReplaceAll([]string{"a", "b", "c", "a"}, "a", "x")

fmt.Println(result)
Output:

[x b c x]

func Reverse

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

Reverse return slice of element order is reversed to the given slice. Play: https://go.dev/play/p/8uI8f1lwNrQ

Example
strs := []string{"a", "b", "c", "d"}

Reverse(strs)

fmt.Println(strs)
Output:

[d c b a]

func RightPadding added in v2.3.1

func RightPadding[T any](slice []T, paddingValue T, paddingLength int) []T

RightPadding adds padding to the right end of a slice. Play: https://go.dev/play/p/0_2rlLEMBXL

Example
nums := []int{1, 2, 3, 4, 5}
padded := RightPadding(nums, 0, 3)
fmt.Println(padded)
Output:

[1 2 3 4 5 0 0 0]

func SetToDefaultIf added in v2.3.0

func SetToDefaultIf[T any](slice []T, predicate func(T) bool) ([]T, int)

SetToDefaultIf sets elements to their default value if they match the given predicate. It retains the positions of the elements in the slice. It returns slice of T and the count of modified slice items Play: https://go.dev/play/p/9AXGlPRC0-A

Example
strs := []string{"a", "b", "a", "c", "d", "a"}
modifiedStrs, count := SetToDefaultIf(strs, func(s string) bool { return "a" == s })
fmt.Println(modifiedStrs)
fmt.Println(count)
Output:

[ b  c d ]
3

func Shuffle

func Shuffle[T any](slice []T) []T

Shuffle the slice. Play: https://go.dev/play/p/YHvhnWGU3Ge

func Some

func Some[T any](slice []T, predicate func(index int, item T) bool) bool

Some return true if any of the values in the list pass the predicate function. Play: https://go.dev/play/p/4pO9Xf9NDGS

Example
nums := []int{1, 2, 3, 5}

isEven := func(i, num int) bool {
	return num%2 == 0
}

result := Some(nums, isEven)

fmt.Println(result)
Output:

true

func Sort added in v2.1.11

func Sort[T constraints.Ordered](slice []T, sortOrder ...string)

Sort sorts a slice of any ordered type(number or string), use quick sort algrithm. default sort order is ascending (asc), if want descending order, set param `sortOrder` to `desc`. Play: https://go.dev/play/p/V9AVjzf_4Fk

Example
nums := []int{1, 4, 3, 2, 5}

Sort(nums)

fmt.Println(nums)
Output:

[1 2 3 4 5]

func SortBy added in v2.1.11

func SortBy[T any](slice []T, less func(a, b T) bool)

SortBy sorts the slice in ascending order as determined by the less function. This sort is not guaranteed to be stable. Play: https://go.dev/play/p/DAhLQSZEumm

Example
type User struct {
	Name string
	Age  uint
}

users := []User{
	{Name: "a", Age: 21},
	{Name: "b", Age: 15},
	{Name: "c", Age: 100}}

SortBy(users, func(a, b User) bool {
	return a.Age < b.Age
})

fmt.Println(users)
Output:

[{b 15} {a 21} {c 100}]

func SortByField

func SortByField[T any](slice []T, field string, sortType ...string) error

SortByField return sorted slice by field slice element should be struct, field type should be int, uint, string, or bool default sortType is ascending (asc), if descending order, set sortType to desc This function is deprecated, use Sort and SortBy for replacement. Play: https://go.dev/play/p/fU1prOBP9p1

Example
type User struct {
	Name string
	Age  uint
}

users := []User{
	{Name: "a", Age: 21},
	{Name: "b", Age: 15},
	{Name: "c", Age: 100}}

err := SortByField(users, "Age", "desc")
if err != nil {
	return
}

fmt.Println(users)
Output:

[{c 100} {a 21} {b 15}]

func StringSlice

func StringSlice(slice any) []string

StringSlice convert param to slice of string. This function is deprecated, use generics feature of go1.18+ for replacement. Play: https://go.dev/play/p/W0TZDWCPFcI

Example
strs := []interface{}{"a", "b", "c"}

result := StringSlice(strs) //[]string{"a", "b", "c"}
fmt.Println(result)
Output:

[a b c]

func SymmetricDifference added in v2.0.3

func SymmetricDifference[T comparable](slices ...[]T) []T

SymmetricDifference oppoiste operation of intersection function. Play: https://go.dev/play/p/h42nJX5xMln

Example
nums1 := []int{1, 2, 3}
nums2 := []int{1, 2, 4}

result := SymmetricDifference(nums1, nums2)

fmt.Println(result)
Output:

[3 4]

func ToSlice added in v2.1.1

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

ToSlice returns a slices of a variable parameter transformation. Play: https://go.dev/play/p/YzbzVq5kscN

Example
result := ToSlice("a", "b", "c")

fmt.Println(result)
Output:

[a b c]

func ToSlicePointer added in v2.1.1

func ToSlicePointer[T any](items ...T) []*T

ToSlicePointer returns a pointer to the slices of a variable parameter transformation. Play: https://go.dev/play/p/gx4tr6_VXSF

Example
str1 := "a"
str2 := "b"

result := ToSlicePointer(str1, str2)

expect := []*string{&str1, &str2}

isEqual := reflect.DeepEqual(result, expect)

fmt.Println(isEqual)
Output:

true

func Union

func Union[T comparable](slices ...[]T) []T

Union creates a slice of unique elements, in order, from all given slices. Play: https://go.dev/play/p/hfXV1iRIZOf

Example
nums1 := []int{1, 3, 4, 6}
nums2 := []int{1, 2, 5, 6}

result := Union(nums1, nums2)

fmt.Println(result)
Output:

[1 3 4 6 2 5]

func UnionBy added in v2.1.9

func UnionBy[T any, V comparable](predicate func(item T) V, slices ...[]T) []T

UnionBy is like Union, what's more it accepts iteratee which is invoked for each element of each slice. Play: https://go.dev/play/p/HGKHfxKQsFi

Example
nums := []int{1, 2, 3, 4}

divideTwo := func(n int) int {
	return n / 2
}
result := UnionBy(divideTwo, nums)

fmt.Println(result)
Output:

[1 2 4]

func Unique

func Unique[T comparable](slice []T) []T

Unique remove duplicate elements in slice. Play: https://go.dev/play/p/AXw0R3ZTE6a

Example
result := Unique([]string{"a", "a", "b"})
fmt.Println(result)
Output:

[a b]

func UniqueBy added in v2.1.0

func UniqueBy[T any, U comparable](slice []T, iteratee func(item T) U) []T

UniqueBy removes duplicate elements from the input slice based on the values returned by the iteratee function. The function maintains the order of the elements. Play: todo

Example
nums := []int{1, 2, 3, 4, 5, 6}
result := UniqueBy(nums, func(val int) int {
	return val % 3
})

fmt.Println(result)
Output:

[1 2 3]

func UniqueByComparator added in v2.3.3

func UniqueByComparator[T comparable](slice []T, comparator func(item T, other T) bool) []T

UniqueByComparator removes duplicate elements from the input slice using the provided comparator function. The function maintains the order of the elements. Play: todo

Example
uniqueNums := UniqueByComparator([]int{1, 2, 3, 1, 2, 4, 5, 6, 4}, func(item int, other int) bool {
	return item == other
})

caseInsensitiveStrings := UniqueByComparator([]string{"apple", "banana", "Apple", "cherry", "Banana", "date"}, func(item string, other string) bool {
	return strings.ToLower(item) == strings.ToLower(other)
})

fmt.Println(uniqueNums)
fmt.Println(caseInsensitiveStrings)
Output:

[1 2 3 4 5 6]
[apple banana cherry date]

func UniqueByConcurrent added in v2.3.3

func UniqueByConcurrent[T comparable](slice []T, comparator func(item T, other T) bool, numThreads int) []T

UniqueByParallel removes duplicate elements from the slice by parallel The comparator function is used to compare the elements The numThreads parameter specifies the number of threads to use If numThreads is less than or equal to 0, it will be set to 1 The comparator function should return true if the two elements are equal Play: todo

Example
nums := []int{1, 2, 3, 1, 2, 4, 5, 6, 4, 7}
comparator := func(item int, other int) bool { return item == other }

result := UniqueByConcurrent(nums, comparator, 4)

fmt.Println(result)
Output:

[1 2 3 4 5 6 7]

func UniqueByField added in v2.3.2

func UniqueByField[T any](slice []T, field string) ([]T, error)

UniqueByField remove duplicate elements in struct slice by struct field. Play: https://go.dev/play/p/6cifcZSPIGu

Example
type User struct {
	ID   int    `json:"id"`
	Name string `json:"name"`
}

users := []User{
	{ID: 1, Name: "a"},
	{ID: 2, Name: "b"},
	{ID: 1, Name: "c"},
}

result, err := UniqueByField(users, "ID")
if err != nil {
}

fmt.Println(result)
Output:

[{1 a} {2 b}]

func UpdateAt

func UpdateAt[T any](slice []T, index int, value T) []T

UpdateAt update the slice element at index. Play: https://go.dev/play/p/f3mh2KloWVm

Example
result1 := UpdateAt([]string{"a", "b", "c"}, -1, "1")
result2 := UpdateAt([]string{"a", "b", "c"}, 0, "1")
result3 := UpdateAt([]string{"a", "b", "c"}, 1, "1")
result4 := UpdateAt([]string{"a", "b", "c"}, 2, "1")
result5 := UpdateAt([]string{"a", "b", "c"}, 3, "1")

fmt.Println(result1)
fmt.Println(result2)
fmt.Println(result3)
fmt.Println(result4)
fmt.Println(result5)
Output:

[a b c]
[1 b c]
[a 1 c]
[a b 1]
[a b c]

func Without

func Without[T comparable](slice []T, items ...T) []T

Without creates a slice excluding all given items. Play: https://go.dev/play/p/bwhEXEypThg

Example
result := Without([]int{1, 2, 3, 4}, 1, 2)

fmt.Println(result)
Output:

[3 4]

Types

This section is empty.

Jump to

Keyboard shortcuts

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