Understanding .map() vs .flat_map() in Rust with a Simple Analogy
Different between .map() and .flat_map() in RUST
fn main() {
let numbers = vec![1, 2, 3];
// Using `map()`
let mapped: Vec<Vec<i32>> = numbers.iter().map(|&n| vec![n, n * 10]).collect();
println!("{:?}", mapped); // [[1, 10], [2, 20], [3, 30]]
// Using `flat_map()`
let flat_mapped: Vec<i32> = numbers.iter().flat_map(|&n| vec![n, n * 10]).collect();
println!("{:?}", flat_mapped); // [1, 10, 2, 20, 3, 30]
}
.map(): Each item stays in its own package (nested boxes)
Imagine you order 3 items, and the delivery guy wraps each item separately inside its own package.
.flat_map(): The delivery guy removes extra boxes (flattens them)
Instead of putting each item in a separate box, he puts everything in one big box—no extra packaging!
Use .map() when you still want to keep items separate (nested lists).
Use .flat_map() when you want to merge everything into one (remove nesting).
PICTUTRE FOR MORE DETAILS
Top comments (0)