How to flatten a 2 dimensions i32 vector?

Hello :wave:

I'm trying to flatten a 2 dimensions vector. I looked through the documentation and I found flat_map but it seems I'm doing something wrong :confused:

The compiler gives me this error:

.collect();
^^^^^^^ a collection of type std::vec::Vec<i32> cannot be built from an iterator over elements of type &{integer}

The 2 dimensions vector:

[[17, 16, 15, 14, 13], [18, 5, 4, 3, 12], [19, 6, 1, 2, 11], [20, 7, 8, 9, 10], [21, 22, 23, 24, 25]]

The source code:

let nested_array = [[17, 16, 15, 14, 13], [18, 5, 4, 3, 12], [19, 6, 1, 2, 11], [20, 7, 8, 9, 10], [21, 22, 23, 24, 25]];
let flatten_array: Vec<i32> = nested_array
                        .iter()
                        .flat_map(|array| array.iter())
                        .collect();
println!("{:?}", flatten_array);

Thanks in advance!

You can add cloned() to get i32s back, rather than &i32. Rust Playground

1 Like

Thank you @vitalyd! :+1: