Propogate errors from iter filter

Hello! I am using a filter (instead of filter_map) very similar to this: https://stackoverflow.com/a/75880545/2561501

In my particular case there is the possibility of an error because of OsStr to Str conversion in the filter. Is there a way to propagate errors from the filter?

I guess you could do the conversion first in a call to map and then filter the results for errors and the condition you want to filter successful conversions by. Then you can short-circuit on the first error encountered during the conversion by collecting the results in a Result<Vec<String>, Error>:

use std::ffi::OsString;

fn main() {
    let v: Vec<OsString> = vec!["hello".into(), "hallo".into(), "hola".into()];

    let res: Result<Vec<String>, OsString> = v
        .into_iter()
        .map(|o| o.into_string())
        .filter(|s| s.is_err() || s.as_ref().unwrap() == "hello")
        .collect();

    assert_eq!(res, Ok(vec!["hello".to_owned()]));
}

Playground.

1 Like