Skip to content

Instantly share code, notes, and snippets.

@Th3Shadowbroker
Created July 16, 2023 17:33
Show Gist options
  • Save Th3Shadowbroker/c16c4f3338cd9cc3966e7777d01ce503 to your computer and use it in GitHub Desktop.
Save Th3Shadowbroker/c16c4f3338cd9cc3966e7777d01ce503 to your computer and use it in GitHub Desktop.
Example for splitting a slice of any type into batches with predefined sizes. The size of the last slice will be adjustes to the left over elements.
func SplitIntoBatches[T any](slice []T, batchSize int) [][]T {
var batches = make([][]T, 0)
var limit = len(slice) - 1
for i := 0; i < len(slice); i += batchSize {
var start = i
var end = i + batchSize
if end > limit {
batches = append(batches, slice[start:limit+1])
} else {
batches = append(batches, slice[start:end])
}
}
return batches
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment