Trait resiter::try_filter_map::TryFilterMap
source · pub trait TryFilterMap<O, E>: Sized {
// Required methods
fn try_filter_map_ok<F, O2>(self, _: F) -> TryFilterMapOk<Self, F> ⓘ
where F: FnMut(O) -> Option<Result<O2, E>>;
fn try_filter_map_err<F, E2>(self, _: F) -> TryFilterMapErr<Self, F> ⓘ
where F: FnMut(E) -> Option<Result<O, E2>>;
}
Expand description
Extension trait for Iterator<Item = Result<O, E>>
to selectively transform and map Oks and Errors.
Required Methods§
sourcefn try_filter_map_ok<F, O2>(self, _: F) -> TryFilterMapOk<Self, F> ⓘwhere
F: FnMut(O) -> Option<Result<O2, E>>,
fn try_filter_map_ok<F, O2>(self, _: F) -> TryFilterMapOk<Self, F> ⓘwhere F: FnMut(O) -> Option<Result<O2, E>>,
Equivalent to Iterator::filter_map on all Ok
values.
The filter function can fail with a result and turn an
Result::Ok into a Result::Err
use std::str::FromStr;
use resiter::try_filter_map::TryFilterMap;
let filter_mapped: Vec<_> = vec![
Ok("1"),
Err("2".to_owned()),
Ok("a"), // will become an error
Err("4".to_owned()),
Ok("5"), // will be filtered out
Err("b".to_owned()),
Err("8".to_owned()),
]
.into_iter()
.try_filter_map_ok(|txt| {
match usize::from_str(txt).map_err(|e| e.to_string()) {
Err(e) => Some(Err(e)),
Ok(u) => {
if u < 3 {
Some(Ok(u))
} else {
None
}
}
}
})
.collect();
assert_eq!(
filter_mapped,
[
Ok(1),
Err("2".to_owned()),
Err("invalid digit found in string".to_owned()),
Err("4".to_owned()),
Err("b".to_owned()),
Err("8".to_owned())
]
);
sourcefn try_filter_map_err<F, E2>(self, _: F) -> TryFilterMapErr<Self, F> ⓘwhere
F: FnMut(E) -> Option<Result<O, E2>>,
fn try_filter_map_err<F, E2>(self, _: F) -> TryFilterMapErr<Self, F> ⓘwhere F: FnMut(E) -> Option<Result<O, E2>>,
Equivalent to Iterator::filter_map on all Err
values.
The filter function can fail with a result and turn a
Result::Err into a Result::Ok
use std::str::FromStr;
use resiter::try_filter_map::TryFilterMap;
let filter_mapped: Vec<_> = vec![
Ok("1".to_owned()),
Err("2".to_owned()), // will become ok
Ok("a".to_owned()),
Err("4".to_owned()), // will be removed
Ok("5".to_owned()),
Err("b".to_owned()), // will be an error
Err("8".to_owned()), // will be removed
]
.into_iter()
.try_filter_map_err(|txt| {
match usize::from_str(&txt).map_err(|e| e.to_string()) {
Err(e) => Some(Err(e)),
Ok(u) => {
if u < 3 {
Some(Ok(u.to_string()))
} else {
None
}
}
}
})
.collect();
assert_eq!(
filter_mapped,
[
Ok("1".to_owned()),
Ok("2".to_owned()),
Ok("a".to_owned()),
Ok("5".to_owned()),
Err("invalid digit found in string".to_owned()),
]
);