I am trying to collect data into Result<Vec_>>
from data that has nested vectors. Consider the following code:
type Result<T> = std::result::Result<T, String>;
fn f(x: u32) -> Result<Vec<u32>> {
Ok(vec![x, x, x])
}
fn main() {
let sources = [1, 2, 3];
let out1: Vec<Result<Vec<u32>>> = sources.iter().map(|x| f(*x)).collect();
let out2: Result<Vec<Vec<u32>>> = sources.iter().map(|x| f(*x)).collect();
// let out3: Result<Vec<u32>> = sources.iter().map(|x| f(*x)).collect();
}
Both out1
and out2
compile correctly, but what I would really like to get is a variation of out2
where the two nested vectors are flattened into one. If I try to use out3
, I get the following error:
error[E0277]: a collection of type `std::vec::Vec<u32>` cannot be built from an iterator over elements of type `std::vec::Vec<u32>`
--> src/main.rs:11:64
|
11 | let out3: Result<Vec<u32>> = sources.iter().map(|x| f(*x)).collect();
| ^^^^^^^ a collection of type `std::vec::Vec<u32>` cannot be built from `std::iter::Iterator<Item=std::vec::Vec<u32>>`
|
= help: the trait `std::iter::FromIterator<std::vec::Vec<u32>>` is not implemented for `std::vec::Vec<u32>`
= note: required because of the requirements on the impl of `std::iter::FromIterator<std::result::Result<std::vec::Vec<u32>, std::string::String>>` for `std::result::Result<std::vec::Vec<u32>, std::string::String>`
How do I get to the flattened Result<Vec<_>>
without building intermediate structures?