I know about join
and connec
.
However, suppose we have:
let x: Vec<Vec<u8>> = ...;
is there anyway to construct a y: Vec<u8>
that joins/connects all the lines of x
via inserting \n
after each line?
I know about join
and connec
.
However, suppose we have:
let x: Vec<Vec<u8>> = ...;
is there anyway to construct a y: Vec<u8>
that joins/connects all the lines of x
via inserting \n
after each line?
let joined: Vec<u8> = x.iter()
.flat_map(|v| v.iter().cloned().chain(std::iter::once('\n' as u8)))
.collect();
In case this looks unfamiliar to you, here it is with detailed comments:
let joined: Vec<u8> =
x.iter() // Iterator<&Vec<u8>>
.flat_map(|v: &Vec<u8>| {
v.iter() // Iterator<&u8>
.cloned() // -> Iterator<u8>
.chain(std::iter::once('\n' as u8)) // -> Iterator<u8> ending with with '\n'
})
// `flat_map` above produces an Iterator<u8>.
// In comparison, `map` would have produced a Iterator<Iterator<u8>>.
// So you can think of `flat_map` as kinda "flattening" otherwise
// nested iterators.
.collect(); // -> Vec<u8>
This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.