Skip to content

Instantly share code, notes, and snippets.

@eculver
Created May 31, 2019 22:43
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 eculver/4ecceba2ba59b22b9798d6dcff688d5e to your computer and use it in GitHub Desktop.
Save eculver/4ecceba2ba59b22b9798d6dcff688d5e to your computer and use it in GitHub Desktop.
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