Documentation
¶
Index ¶
- func ChunkSlice[T any](slice []T, chunkSize int) [][]T
- func Contains[T comparable](arr []T, target T) bool
- func GetJSONTags(v interface{}) []string
- func GetMapKeys[K comparable, V any](m map[K]V) []K
- func ProcessInChunksConcurrently[T any](ctx context.Context, slice []T, chunkSize int, maxConcurrent int, ...) error
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func ChunkSlice ¶ added in v0.9.5
ChunkSlice splits a slice into smaller chunks of the specified size. It returns a slice of slices, where each inner slice has at most chunkSize elements. This is useful for processing large datasets in batches to avoid resource limits.
Example:
numbers := []int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
chunks := ChunkSlice(numbers, 3)
Result:
[[1, 2, 3], [4, 5, 6], [7, 8, 9], [10]]
func Contains ¶
func Contains[T comparable](arr []T, target T) bool
Contains checks if a target item exists in an array of any type.
Example:
names := []string{"Alice", "Bob", "Carol"}
result := Contains(names, "Bob")
Result:
true
func GetJSONTags ¶
func GetJSONTags(v interface{}) []string
GetJSONTags retrieves all JSON tag values from a struct. It returns a slice of JSON tag values extracted from the struct's fields.
Example:
type Person struct {
ID int `json:"id"`
Name string `json:"name"`
Age int `json:"age"`
CreatedAt string `json:"created_at"`
}
p := Person{}
jsonTags := GetJSONTags(p)
Result:
["id", "name", "age", "created_at"]
func GetMapKeys ¶
func GetMapKeys[K comparable, V any](m map[K]V) []K
GetMapKeys is a generic function that extracts all keys from a map and returns them in a slice.
Example:
ageMap := map[string]int{"Alice": 30, "Bob": 25, "Carol": 27}
keys := GetMapKeys(ageMap)
Result:
["Alice", "Bob", "Carol"]
func ProcessInChunksConcurrently ¶ added in v0.9.5
func ProcessInChunksConcurrently[T any]( ctx context.Context, slice []T, chunkSize int, maxConcurrent int, processFn func(chunk []T) error, ) error
ProcessInChunksConcurrently processes a slice in chunks concurrently with a limit on concurrent goroutines. It returns an error if any chunk processing fails. Processing stops immediately on first error via context cancellation. The maxConcurrent parameter controls how many chunks can be processed simultaneously.
Example:
numbers := []int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12}
err := ProcessInChunksConcurrently(ctx, numbers, 3, 3, func(chunk []int) error {
fmt.Printf("Processing chunk: %v\n", chunk)
time.Sleep(100 * time.Millisecond) // Simulate work
return nil
})
Result: Up to 3 chunks processed concurrently
Processing chunk: [1 2 3] Processing chunk: [4 5 6] Processing chunk: [7 8 9] Processing chunk: [10 11 12]
Types ¶
This section is empty.