Generic functions for Slice of Golang. Golang 切片的常用泛型方法。
Need v1.18+
go get github.com/shalldie/gog/gs
All functions are immutable
.
Copies elements from a source slice into a new slice.
newlist := gs.Copy([]int{1})
Reverses the elements into a new slice.
newlist := gs.Reverse([]int{1, 2, 3})
// [3 2 1]
Sort a slice into a new slice.
newlist = gs.Sort([]int{2, 5, 1, 3, 4, 5}, func(t1, t2 int) bool {
return t1 < t2
})
// [1 2 3 4 5 5]
Returns the index of the first occurrence of a value in a slice, or -1 if it is not present.
list := []int{1, 2, 3, 2}
index2 := gs.IndexOf(list, 2)
// 1
index5 := gs.IndexOf(list, 5)
// -1
Returns the index of the last occurrence of a specified value in a slice, or -1 if it is not present.
list := []int{1, 2, 3, 2}
index2 := gs.LastIndexOf(list, 2)
// 3
index5 := gs.LastIndexOf(list, 5)
// -1
Determines whether all the members of a slice satisfy the specified test.
allless4 := gs.Every([]int{1, 2, 3}, func(item, index int) bool {
return item < 4
})
// true
Determines whether the specified callback function returns true for any element of a slice.
hasEven := gs.Some([]int{5, 6, 7}, func(item, index int) bool {
return item%2 == 0
})
// true
Performs the specified action for each element in a slice.
gs.ForEach([]int{1, 2, 3}, func(item, index int) {
println(item)
})
Calls a defined callback function on each element of a slice, and returns a slice that contains the results.
list := gs.Map([]int{5, 6, 7}, func(item, index int) string {
return strconv.Itoa(item)
})
// ["5" "6" "7"]
Returns the elements of a slice that meet the condition specified in a callback function.
list = gs.Filter([]int{1, 2, 3, 4, 5, 6, 7, 8}, func(item, index int) bool {
return item%2 == 0
})
// [2 4 6 8]
Calls the specified callback function for all the elements in a slice. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function.
sum := gs.Reduce([]int{1, 2, 3}, func(previousValue int, currentValue int, currentIndex int) int {
return previousValue + currentValue
}, 0)
// 6
Returns the index of the first element in the slice that satisfies the provided testing function. Otherwise, it returns -1
index := gs.FindIndex([]int{1, 2, 3}, func(item, index int) bool {
return item%2 == 0
})
// 1
Returns the value of the first element in the provided slice that satisfies the provided testing function.
target, err := gs.Find([]int{1, 2, 3}, func(item, index int) bool {
return item%2 == 0
})
if err != nil {
println(target)
// 2
}
MIT