Batch Items Safely With slices.Chunk And cmp.Or
Combine cmp.Or fallback defaults, maps.Clone per-batch isolation, and slices.Chunk iteration to dispatch fixed-size slices cleanly.
Code
package main
import (
"cmp"
"fmt"
"maps"
"slices"
)
func dispatchBatches(items []string, batchSize int, region string, baseMeta map[string]string) {
size := cmp.Or(batchSize, 2)
targetRegion := cmp.Or(region, "us-east-1")
batchNum := 0
for chunk := range slices.Chunk(items, size) {
batchNum++
// Clone prevents batch-local annotations from mutating the caller map
meta := maps.Clone(baseMeta)
meta["region"] = targetRegion
meta["batch"] = fmt.Sprintf("%d", batchNum)
fmt.Printf("batch %s (%s): %v meta=%v\n", meta["batch"], targetRegion, chunk, meta)
}
}
func main() {
defaults := map[string]string{"service": "ingest"}
jobs := []string{"j1", "j2", "j3", "j4", "j5"}
dispatchBatches(jobs, 0, "", defaults)
fmt.Println("caller map unchanged:", defaults)
}Execution breakdown — Batch Items Safely With slices.Chunk And cmp.Or
Under the hood: the functions dispatchBatches and main.
One loop does the cycling here: for chunk := range slices.Chunk(items, size).
Points of care
- Built-in APIs only, so there is no supply chain to vet.
Using it
Implementation revolves around signature func dispatchBatches(items []string, batchSize int, region string, baseMeta map[string]string)
The run emits 2 labeled sections — batch, caller map unchanged: — one per step.
main calls 1 helper in sequence: dispatchBatches.
Key statements
func main() {
defaults := map[string]string{"service": "ingest"}
jobs := []string{"j1", "j2", "j3", "j4", "j5"}
dispatchBatches(jobs, 0, "", defaults)
fmt.Println("caller map unchanged:", defaults)
}
meta["batch"] = fmt.Sprintf("%d", batchNum)
Interactive Tools for This Topic
cURL to Python & Go ConverterTranslate curl CLI commands with headers, auth, JSON bodies, and timeouts into ready-to-run Python requests and Go net/http client code snippets.Dotenv File ParserParse .env file content into a JSON object, handling comments, export prefixes, single quotes, and double-quoted escape sequences.INI File ParserParse INI configuration files into nested JSON with section objects, global keys, and both semicolon and hash comment support.JSON to TOML ConverterTurn a JSON object into TOML, emitting nested objects as tables and arrays of objects as array-of-tables blocks.
FAQ
- What does Batch Items Safely With slices.Chunk And cmp.Or print when run?
- No setup needed: run the file and look for labeled lines like `batch`, `caller map unchanged:` in the output.
Report a problem with this exampleOpens a pre-filled issue on GitHub.