1

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?

Listerone
  • 1,381
  • 1
  • 11
  • 25
  • It looks like your question might be answered by the answers of [How do I perform iterator computations over iterators of Results without collecting to a temporary vector?](https://stackoverflow.com/q/48841367/155423). If not, please **[edit]** your question to explain the differences. Otherwise, we can mark this question as already answered. – Shepmaster Aug 27 '19 at 17:46
  • The duplicate applied to your case: `itertools::process_results(sources.iter().copied().map(f), |i| i.flatten().collect())` – Shepmaster Aug 27 '19 at 17:47

0 Answers0