0

Consider this code :

use std::io::Result;
use std::fs::{read_dir, DirEntry};

fn f() -> Result<Vec<DirEntry>> {
    read_dir("some_dir")?
        .map(|x| {
            match x {
                Ok(s) => s,
                Err(e) => return Err(e),
            }
        })
        .collect()
}

gives me a compilation error :

error[E0308]: mismatched types
 --> src/lib.rs:9:26
  |
9 |                 Ok(s) => s,
  |                          ^ expected enum `std::result::Result`, found struct `std::fs::DirEntry`
  |
  = note: expected type `std::result::Result<_, std::io::Error>`
             found type `std::fs::DirEntry`

This makes sense, since I am returning inside a closure so the return Err(e) is a return of the closure not the f function. How do I do this correctly though? I don't want to use for loops, as I am trying to do this functionally. My first attempt was writing something like .map(|x| x?) but of course that doesn't work for the same reasons. Please help.

DawidKubis
  • 31
  • 2
  • 1
    Does this answer your question? [How do I stop iteration and return an error when Iterator::map returns a Result::Err?](https://stackoverflow.com/questions/26368288/how-do-i-stop-iteration-and-return-an-error-when-iteratormap-returns-a-result) – justinas Dec 31 '19 at 11:52
  • It seems that you'd like to either return a `Vec` if all results are successful or return the first error if any errors are found. The `collect()` trick that turns `Vec` into `Result, E>` in the linked question should do the trick. – justinas Dec 31 '19 at 11:54
  • @justinas thanks, that's exactly what i need. – DawidKubis Dec 31 '19 at 12:14

0 Answers0