Snippets: Golang: Split Slice into Chunks

 28th December 2021 at 5:28pm
func chunkSlice(slice []int, chunkSize int) [][]int {
	var chunks [][]int
	for i := 0; i < len(slice); i += chunkSize {
		end := i + chunkSize

		// necessary check to avoid slicing beyond
		// slice capacity
		if end > len(slice) {
			end = len(slice)
		}

		chunks = append(chunks, slice[i:end])
	}

	return chunks
}

来自:https://freshman.tech/snippets/go/split-slice-into-chunks/