go 1.18でchunk?が書きやすくなったのでメモ。
import (
"fmt"
)
func chunks[T any](l []T, n int) chan []T {
ch := make(chan []T)
go func() {
for i := 0; i < len(l); i += n {
fromIdx := i
toIdx := i + n
if toIdx > len(l) {
toIdx = len(l)
}
ch <- l[fromIdx:toIdx]
}
close(ch)
}()
return ch
}
func main() {
mm := []map[string]interface{}{
{"a": 1, "b": 2},
{"a": 3, "b": 4},
{"a": 5, "b": 6},
{"a": 7, "b": 8},
{"a": 9, "b": 10},
}
for m := range chunks(mm, 3) {
log.Printf("m %v", m)
}
nums := []int{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}
for n := range chunks(nums, 3) {
log.Printf("n %v", n)
}
}