Starting from this code (Playground link)
enum Kind {
Foo,
Bar,
Baz,
}
struct Element {
kind: Kind,
value: i32,
}
fn main() {
let v = vec![
Element { kind: Kind::Foo, value: 1 },
Element { kind: Kind::Bar, value: 2 },
Element { kind: Kind::Baz, value: 3 },
Element { kind: Kind::Bar, value: 4 },
Element { kind: Kind::Baz, value: 5 },
];
}
I'd like to filter and group the elements of v
by their kind
, discarding some types. So in the end I'd like to get two Vec
s, looking like this:
assert!(foos, vec![
Element { kind: Kind::Foo, value: 1 },
]);
assert!(bars, vec![
Element { kind: Kind::Bar, value: 2 },
Element { kind: Kind::Bar, value: 4 },
]);
I fiddled around with unzip()
:
let (foos, bars): (Vec<_>, Vec<_>) v.into_iter().map(|el| {
match el.kind {
Kind::Foo => (el, None),
Kind::Foo => (None, el),
_ => (None, None),
}
}).unzip();
but I would still have to get rid of the Option
s.