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

  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> {

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> {

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.


There is a real concat() method though, found here:

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.