luminyra
Guides

Slices, sets, and maps

Group and batch orders, transform map values, and compare sets from two time periods.

Group and batch orders

GroupBy creates a map keyed by customer. Partition separates paid and unpaid orders. The example uses maps.Keys and slices.Sorted to produce a stable order from the map.

coll/examples/slices/main.go
// GroupBy returns a map, whose iteration order is unspecified; sort the
// keys for stable output.
byCustomer := coll.GroupBy(orders, func(o order) string { return o.Customer })
for _, name := range slices.Sorted(maps.Keys(byCustomer)) {
	fmt.Printf("%s: %d orders\n", name, len(byCustomer[name]))
}

settled, pending := coll.Partition(orders, isPaid)
fmt.Printf("%d paid, %d pending\n", len(settled), len(pending))
View on GitHub

Use the standard-library slices.Chunk to batch an existing slice of order IDs.

coll/examples/slices/main.go
// For a slice that is already in memory, the standard slices.Chunk
// batches it without copying.
for batch := range slices.Chunk(ids, 2) {
	fmt.Println("batch:", batch)
}
View on GitHub

Transform map values

Copy the inventory map with maps.Clone, then remove out-of-stock entries with maps.DeleteFunc. MapValues preserves the keys and turns quantities into readable labels.

coll/examples/maps-sets/main.go
// Filtering a map is covered by the standard library: clone it, then
// remove entries with maps.DeleteFunc.
inStock := maps.Clone(stock)
maps.DeleteFunc(inStock, func(_ string, n int) bool { return n == 0 })

// MapValues passes only the value to the callback and keeps the keys.
labels := coll.MapValues(inStock, func(n int) string { return fmt.Sprintf("%d in stock", n) })
View on GitHub

Compare two sets

Intersect finds members present in both periods. The order of the inputs to Difference determines whether you get departures or additions. Union merges and deduplicates in order of first appearance.

coll/examples/maps-sets/main.go
lastWeek := []string{"alice", "bob", "carol", "bob"}
thisWeek := []string{"bob", "dave", "carol", "erin"}

retained := coll.Intersect(lastWeek, thisWeek) // active both weeks, deduplicated
churned := coll.Difference(lastWeek, thisWeek) // active last week only
joined := coll.Difference(thisWeek, lastWeek)  // new this week
everyone := coll.Union(lastWeek, thisWeek)     // everyone, in order of first appearance
View on GitHub

On this page