Search code examples
rustvectorstructcollectionsiterator

Partition struct collection into member collection


I want to convert a collection of struct type to collection of struct's member type.

struct Foo {
    a: String,
    b: i64,
    c: f64,
}

fn main() {
    let foo: Vec<Foo>;
    let (a, b, c): (Vec<&String>, Vec<&i64>, Vec<&f64>) = foo.iter(); // Not sure how.
}

Solution

  • You can use Iterator::unzip():

    let foo: Vec<Foo>;
    let ((a, b), c): ((Vec<&str>, Vec<i64>), Vec<f64>) =
        foo.iter().map(|v| ((v.a.as_str(), v.b), v.c)).unzip();