实现说明
切片笛卡尔积组合以函数 main为骨架。
迭代发生在 for _, k := range ks 内部——循环之外的语句只执行一遍。
使用要点
- 跑完文件,输出里会留下标记——
mixed types:。
常见问题
运行「切片笛卡尔积组合」会打印什么?
整个文件跑完,输出行以 mixed types: 这类前缀开头。
核心语句
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)
}
代码示例
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)
}