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.

GoConfig Management

Code

snippet
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

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.