How to split a slice into equally sized chunks in Go
Created
Modified
Using for Loop
The easiest method involves iterating over the slice and incrementing by the chunk size. An implementation is shown in the section below.
package main
import "fmt"
func chunkSlice(slice []int, chunkSize int) ([][]int, error) {
chunks := make([][]int, 0, (len(slice)+chunkSize-1)/chunkSize)
for chunkSize < len(slice) {
slice, chunks = slice[chunkSize:], append(chunks, slice[0:chunkSize:chunkSize])
}
chunks = append(chunks, slice)
return chunks, nil
}
func main() {
slice := []int{1, 2, 3, 4, 5, 6, 7}
chunks, _ := chunkSlice(slice, 3)
fmt.Println(chunks)
}
[[1 2 3] [4 5 6] [7]]
You can use reflect.TypeOf for any []T.
Another variant
A general solution to split a slice to into sub-slices of equal length.
package main
import "fmt"
func chunkSlice(slice []int, chunkSize int) ([][]int, error) {
chunks := make([][]int, 0, (len(slice)+chunkSize-1)/chunkSize)
var j int
for i := 0; i < len(slice); i += chunkSize {
j += chunkSize
if j > len(slice) {
j = len(slice)
}
chunks = append(chunks, slice[i:j])
}
return chunks, nil
}
func main() {
slice := []int{1, 2, 3, 4, 5, 6, 7}
chunks, _ := chunkSlice(slice, 3)
fmt.Println(chunks)
}
[[1 2 3] [4 5 6] [7]]
Note that if the slice length is not divisible by the chunk size, the last chunk will be less than the chunk size.