Flat map transforms each item in a collection and flattens the resulting nested collections into a single list in one step.
Use flat_map to transform each element of a collection into a new collection and then flatten the result into a single collection. It combines map and flatten into one operation.
fn main() {
let numbers = vec![vec![1, 2], vec![3, 4], vec![5, 6]];
let result: Vec<i32> = numbers.iter()
.flat_map(|arr| arr.iter().map(|n| n * 2))
.collect();
println!("{:?}", result); // [2, 4, 6, 8, 10, 12]
}
Flat map is a tool that lets you change items in a list and then automatically merge the new lists into one big list. Think of it like opening several small boxes, taking out the items, and putting them all into one large box without having to do it in two separate steps. You use it when you need to transform data and remove an extra layer of nesting at the same time.