4

Golang - Loop over slice in batches (run something in parallel on a sub-slice)

 8 months ago
source link: https://gist.github.com/VojtechVitek/00f8f22b0ab3ec221815fcd78f244edd
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

Loop over slice in batches (run something in parallel on a sub-slice) · GitHub

Instantly share code, notes, and snippets.

Golang - Loop over slice in batches (run something in parallel on a sub-slice)
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)

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).

Author

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

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

Here is a generic version:

func batchSlice[T any](in []T, size int) (out [][]T) {
	out = make([][]T, 0)

	if size == 0 {
		panic("slice batch size is 0")
	}

	for i := 0; i < len(in); i = i + size {
		j := i + size
		if j > len(in) {
			j = len(in)
		}
		out = append(out, in[i:j])
	}

	return
}

tests: https://go.dev/play/p/6szpCDNQsko


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK