Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Golang - Loop over slice in batches (run something in parallel on a sub-slice)
package main
import "fmt"
func main() {
slice := make([]int, 159)
// Split the slice into batches of 20 items.
batch := 20
for i := 0; i < len(slice); i += batch {
j := i + batch
if j > len(slice) {
j = len(slice)
}
fmt.Println(slice[i:j]) // Process the batch.
}
// Try it at https://play.golang.org/p/mgd814w8xx6
}
@robertotambunan
Copy link

robertotambunan commented Aug 28, 2018

for i := 0; i < len(recipients); i += batch {
		j := i + batch
		if j >= len(recipients) {
			j = len(recipients) - 1
		}
		fmt.Printf("recipients[%v:%v]\n", i, j)
}

I think you're expecting to iterate with this condition i < len(recipients)

Loading

@sangheee
Copy link

sangheee commented Mar 16, 2019

if j >= len(recipients) {
     j = len(recipients) 
}

When j is greater than or equal to len recipients), j is appropriate for len(recipients).
Because slice slicing does not include the slicing end point( recipients[i: j] are include i ~ j-1 in fact).

Loading

@VojtechVitek
Copy link
Author

VojtechVitek commented Mar 26, 2019

Guys, the gist works correctly. I added a link to https://play.golang.org/p/mgd814w8xx6 so you can play around with it.

Loading

@gmonk
Copy link

gmonk commented Aug 12, 2020

Works like a charm .. This saved me so much time.. Thank you

Loading

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment