DEV Community

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

Posted on

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)

AWS Security LIVE!

Join us for AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

Learn More

👋 Kindness is contagious

Engage with a wealth of insights in this thoughtful article, valued within the supportive DEV Community. Coders of every background are welcome to join in and add to our collective wisdom.

A sincere "thank you" often brightens someone’s day. Share your gratitude in the comments below!

On DEV, the act of sharing knowledge eases our journey and fortifies our community ties. Found value in this? A quick thank you to the author can make a significant impact.

Okay