DEV Community

Cover image for Understanding .map() vs .flat_map() in Rust with a Simple Analogy
MORDECAI ETUKUDO
MORDECAI ETUKUDO

Posted on

1 1

Understanding .map() vs .flat_map() in Rust with a Simple Analogy

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]
}

Enter fullscreen mode Exit fullscreen mode

.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.

Image description

.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!

Image description

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

Hostinger image

Get n8n VPS hosting 3x cheaper than a cloud solution

Get fast, easy, secure n8n VPS hosting from $4.99/mo at Hostinger. Automate any workflow using a pre-installed n8n application and no-code customization.

Start now

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay