Cartesian Product With flat_map And move Closures

flat_map drives a move closure per outer item over the whole inner list, producing the cartesian product as owned combos in one collect.

RustData Integrity

Code

rustsnippet
26 lines
#[derive(Debug)]
struct Combo {
    size: &'static str,
    milk: &'static str,
}

fn main() {
    let sizes = ["S", "M"];
    let milks = ["oat", "whole"];

    // cartesian product:flat_map 让外层每个元素驱动内层整列,
    // move closures 把当前 size 复制进内层,两处借用都不会悬垂
    let combos: Vec<Combo> = sizes
        .iter()
        .copied()
        .flat_map(|size| {
            milks
                .iter()
                .copied()
                .map(move |milk| Combo { size, milk })
        })
        .collect();

    println!("{combos:?}");
    println!("{} x {} = {}", sizes.len(), milks.len(), combos.len());
}

How it works

Under the hood: the function main.

What to watch for

  • No dependencies section needed; the standard library is the whole story.

Core lines

.map(move |milk| Combo { size, milk })
})
.collect();

Interactive Tools for This Topic

FAQ

How do you run Cartesian Product With flat_map And move Closures?
Execute it straight away — the program needs nothing beyond the runtime.