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
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
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:
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
You can try out both implementations on the Go Playground.
Thanks for reading, and happy coding!