Skip to content

Instantly share code, notes, and snippets.

@enihsyou
Created December 17, 2020 10:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save enihsyou/41744dbda8675ec8aad73920dd6055ac to your computer and use it in GitHub Desktop.
Save enihsyou/41744dbda8675ec8aad73920dd6055ac to your computer and use it in GitHub Desktop.
How to iterate through slice in chunk
// int64 version, iterate through slice in chunk, breaks on first error.
func IterateSliceInChunk(slice []int64, chunkSize int, work func([]int64) error) error {
if chunkSize < 1 {
panic("chunk size is below one")
}
var offset = 0
var err error
for err == nil {
lower, upper := offset, offset+chunkSize
if upper >= len(slice) {
err = work(slice[lower:])
break
} else {
err = work(slice[lower:upper])
offset = upper
}
}
return err
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment