Slices Cross Product Builds Combinations

Build every (size, color) pair from two slices with a generic cross product helper, not just the index-aligned pairs that zip produces.

GoData Integrity

Code

gosnippet
32 lines
package main

import "fmt"

type pair[K, V any] struct {
	first  K
	second V
}

// crossProduct builds every (k, v) combination from two slices.
func crossProduct[K, V any](ks []K, vs []V) []pair[K, V] {
	out := make([]pair[K, V], 0, len(ks)*len(vs))
	for _, k := range ks {
		for _, v := range vs {
			out = append(out, pair[K, V]{k, v})
		}
	}
	return out
}

func main() {
	shirts := []string{"s", "m", "l"}
	colors := []string{"black", "white"}

	// cross product: every pair appears, not just index-aligned ones
	for _, p := range crossProduct(shirts, colors) {
		fmt.Printf("%s/%s\n", p.first, p.second)
	}

	nums := crossProduct([]int{1, 2}, []float64{0.5, 1.5})
	fmt.Println("mixed types:", len(nums), nums[0].first, nums[1].second)
}

What happens on each run — Slices Cross Product Builds Combinations

Structurally, expect the function main and nothing else.

for _, k := range ks is the loop that carries the per-item work.

Caveats

  • Plain standard library: paste the file into a project and it executes as-is.

Putting it to use

Entry signature: func main()

The run emits 1 labeled section — mixed types: — one per step.

Core lines

func crossProduct[K, V any](ks []K, vs []V) []pair[K, V] {
	out := make([]pair[K, V], 0, len(ks)*len(vs))
	for _, k := range ks {
		for _, v := range vs {
			out = append(out, pair[K, V]{k, v})
		}
	}
	return out
}
for _, p := range crossProduct(shirts, colors) {
	fmt.Printf("%s/%s\n", p.first, p.second)
}

Interactive Tools for This Topic

FAQ

What does Slices Cross Product Builds Combinations print when run?
No setup needed: run the file and look for labeled lines like `mixed types:` in the output.