How to split a slice into uniform chunks in Go

Splitting a slice into chunks of uniform sizes is pretty straightforward in most programming languages, and its no different in Go.

There are several approaches for splitting a slice in Go, but the easiest method involves iterating over the slice and incrementing by the chunk size. An implementation is shown in the section below.

Loop through the number of chunks

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
}

Here, a slice called chunks is created to hold the slice chunks. Next, we iterate through the given slice using the number of chunks (as specified by chunkSize), and then append a new chunk to the chunks variable based on a portion of the original slice.

On each iteration, it is necessary to check that upper limit of our chunk does not exceed the slice’s capacity. If it is, we adjust that by setting the end variable to the length of the slice before attempting to pull out the last chunk.

Note that if the slice length is not divisible by the chunk size, the last chunk will be less than the chunk size.

Here’s a slightly different implementation that achieves the same effect:

func chunkSlice(slice []int, chunkSize int) [][]int {
	var chunks [][]int
	for {
		if len(slice) == 0 {
			break
		}

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

		chunks = append(chunks, slice[0:chunkSize])
		slice = slice[chunkSize:]
	}

	return chunks
}

This one relies on modifying the original slice continuously and breaking out of the loop once the slice length reaches zero. The chunk size is also adjusted here to avoid slicing beyond slice’s capacity.

Conclusion

You can try out both implementations on the Go Playground.

Thanks for reading, and happy coding!