Documentation
¶
Overview ¶
Package sliceutil provides utility functions for working with slices
Index ¶
- func Diff[K comparable](before, after []K) ([]K, []K)
- func ErrorToString(data []error) []string
- func Exclude[K comparable](slice []K, items ...K) []K
- func Filter[T any](slice []T, filter func(v T, index int) bool) []T
- func Join[T any](slice []T, sep string) string
- func JoinFunc[T any](slice []T, sep string, f func(v T) string) string
- func Shuffle[T any](slice []T)
- func StringToError(data []string) []error
- func ToAny[T any](data []T) []any
Examples ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func Diff ¶
func Diff[K comparable](before, after []K) ([]K, []K)
Diff returns elements added to and removed from before to produce after
Example ¶
s1 := []int{1, 2, 3, 5, 7, 8}
s2 := []int{2, 3, 5, 6, 7}
added, deleted := Diff(s1, s2)
fmt.Printf("Added: %v\n", Join(added, ", "))
fmt.Printf("Deleted: %v\n", Join(deleted, ", "))
Output: Added: 6 Deleted: 1, 8
func ErrorToString ¶
ErrorToString converts a slice of errors to a slice of strings by calling Error() on each element
Example ¶
s := []error{fmt.Errorf("error1")}
fmt.Printf("%v\n", ErrorToString(s))
Output: [error1]
func Exclude ¶
func Exclude[K comparable](slice []K, items ...K) []K
Exclude returns a copy of slice with all occurrences of items removed
Example ¶
s := []string{"A", "B", "C", "D"}
fmt.Println(Exclude(s, "B", "D"))
Output: [A C]
func Filter ¶
Filter returns a new slice containing only the elements for which predicate returns true, preserving the original order
Example ¶
s := []int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
r := Filter(s, func(v int, index int) bool {
return v%2 == 0
})
fmt.Printf("Result: %v\n", r)
Output: Result: [2 4 6 8 10]
func Join ¶
Join concatenates slice elements into a single string separated by sep. Unlike strings.Join, it supports slices of any type via fmt's %v verb.
Example ¶
s1 := []string{"A", "B", "C", "D"}
s2 := []int{1, 2, 3, 4, 5}
s3 := []any{"John", nil, 183, 98.123, "", false}
fmt.Println(Join(s1, ":"))
fmt.Println(Join(s2, ","))
fmt.Println(Join(s3, ";"))
Output: A:B:C:D 1,2,3,4,5 John;183;98.123;false
func JoinFunc ¶ added in v14.1.2
JoinFunc concatenates elems into a single string separated by sep, applying f to each element before joining.
Example ¶
s := []int{100, 200, 300, 400, 500}
fmt.Println(JoinFunc(s, ":", func(v int) string {
return strconv.FormatInt(int64(v), 30)
}))
Output: 3a:6k:a0:da:gk
func Shuffle ¶
func Shuffle[T any](slice []T)
Shuffle randomizes the order of elements in slice in place
Example ¶
s := []int{1, 2, 3, 4, 5, 6, 7, 8, 9}
Shuffle(s)
fmt.Printf("Result: %v\n", s)
func StringToError ¶
StringToError converts a slice of strings to a slice of errors, wrapping each string with errors.New
Types ¶
This section is empty.