Slice Chunking in Go
Problem:
How to evenly distribute a given slice into multiple slices in Go?
Solution:
To chunk a slice evenly, follow these steps:
Here's a revised version of the code provided in the question:
var divided [][]string chunkSize := (len(logs) + runtime.NumCPU - 1) / runtime.NumCPU for i := 0; i < len(logs); i += chunkSize { end := i + chunkSize if end > len(logs) { end = len(logs) } divided = append(divided, logs[i:end]) }
This updated code creates evenly distributed chunked slices by appending subsets of the original slice to the slice of slices. The chunk size is calculated to ensure that all elements are distributed as evenly as possible.
The above is the detailed content of How to Evenly Distribute a Go Slice into Multiple Chunks?. For more information, please follow other related articles on the PHP Chinese website!