I have a sequence of tuples where each tuple contains another sequences.
To better illustrate the problem, please have a look at the below snippet (Rust Playground):
fn main() {
let data = [
(vec![1, 2, 3], vec!['a']),
(vec![4, 5, 6], vec!['b', 'c'])
];
let res: (Vec<i32>, Vec<char>) = data...?
// res = (vec![1, 2, 3, 4, 5, 6], vec!['a', 'b', 'c']);
}
I would like to iterate data only once to create two Vecs. Each Vec is a concatenation of all the elements within a corresponding tuple’s member.
res is a commented out expected result.
How this can be achieved in Rust?
>Solution :
You can use reduce.
let res: (Vec<i32>, Vec<char>) = data
.into_iter()
.reduce(|(mut acc1, mut acc2), (mut i1, mut i2)| {
acc1.append(&mut i1);
acc2.append(&mut i2);
(acc1, acc2)
})
// An empty sequence will produce `(vec![], vec![])`
.unwrap_or_default();