Skip to content

Instantly share code, notes, and snippets.

@eculver

eculver/batch.go

Created May 31, 2019
Embed
What would you like to do?
Divide slice into batches
// run at: https://play.golang.org/p/bhgYlgGbdHz
package main
import (
"fmt"
)
func main() {
total := 22
batch := 3
batches := [][]string{}
ids := initSlice(total)
for i := 0; i < len(ids); i += batch {
end := i+batch
if end > len(ids) {
end = len(ids)
}
batches = append(batches, ids[i:end])
}
fmt.Println("batches:")
for _, b := range batches {
fmt.Printf("%v", b)
}
}
func initSlice(n int) []string {
res := make([]string, n)
for i := 0; i < n; i++ {
res[i] = fmt.Sprintf("id-%d", i)
}
return res
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment