How to flatten a 2 dimensions i32 vector?


#1

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!


#2

You can add cloned() to get i32s back, rather than &i32. https://play.rust-lang.org/?gist=aff7fbec8539ea55abf9fb0bace63391&version=stable


#3

Thank you @vitalyd! :+1: