Flatten a Vec<Vec<T>> to a Vec<T>

#1
  1. I have searched through https://doc.rust-lang.org/std/vec/struct.Vec.html for flatten.

  2. What is the idiomatic way to write:

pub fn flatten(vv: Vec<Vec<T>>) -> Vec<T> {
  ???
}
#2

lol: what I want is ‘concat’ :slight_smile:

#3

You can write your flatten function as follows:

fn flatten<T>(nested: Vec<Vec<T>>) -> Vec<T> {
    nested.into_iter().flatten().collect()
}

You first convert the outer Vec into an iterator. An iterator then supports the flatten operation and can be converted back into a Vec using collect.

#4

There is a real concat() method though, found here:
https://doc.rust-lang.org/std/slice/trait.SliceConcatExt.html

That’s probably faster than a flattened iterator, unless that’s already been specialized.

#6

Oh, I forgot that concat() has to clone though. If your T::clone() is expensive, or if T doesn’t implement Clone at all, then the flattened iterator may be a better choice after all.