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

  1. I have searched through Vec in std::vec - Rust for flatten.

  2. What is the idiomatic way to write:

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

lol: what I want is 'concat' :slight_smile:

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.

6 Likes

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.

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.

2 Likes