pub trait TryMap<O, E>: Sized {
// Required methods
fn try_map_ok<F, O2>(self, _: F) -> TryMapOk<Self, F> ⓘ
where F: FnMut(O) -> Result<O2, E>;
fn try_map_err<F, E2>(self, _: F) -> TryMapErr<Self, F> ⓘ
where F: FnMut(E) -> 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_map_ok<F, O2>(self, _: F) -> TryMapOk<Self, F> ⓘ
fn try_map_ok<F, O2>(self, _: F) -> TryMapOk<Self, F> ⓘ
Equivalent to Iterator::map on all Ok
values.
The map function can fail with a result and turn a
Result::Ok into a Result::Err
use std::str::FromStr;
use resiter::try_map::TryMap;
let mapped: Vec<_> = vec![
Ok("1"),
Err("2".to_owned()),
Ok("a"), // will become an error
Err("4".to_owned()),
Ok("5"), // will be too high
Err("b".to_owned()),
Err("8".to_owned()),
]
.into_iter()
.try_map_ok(|txt| {
let n = usize::from_str(txt).map_err(|e| e.to_string())?;
if n < 3 {
Ok(n)
}
else {
Err("Too high".to_string())
}
})
.collect();
assert_eq!(
mapped,
[
Ok(1),
Err("2".to_owned()),
Err("invalid digit found in string".to_owned()),
Err("4".to_owned()),
Err("Too high".to_owned()),
Err("b".to_owned()),
Err("8".to_owned())
]
);
Sourcefn try_map_err<F, E2>(self, _: F) -> TryMapErr<Self, F> ⓘ
fn try_map_err<F, E2>(self, _: F) -> TryMapErr<Self, F> ⓘ
Equivalent to Iterator::map on all Err
values.
The map function can fail with a result and turn a
Result::Err into a Result::Ok or another Result::Err
possibly changing it’s error type
use std::str::FromStr;
use resiter::try_map::TryMap;
let mapped: Vec<_> = vec![
Ok(1),
Err("2".to_owned()), // will become ok
Ok(3),
Err("4".to_owned()), // will be "Too high"
Ok(5),
Err("b".to_owned()), // will be an error
Err("8".to_owned()), // will be "Too high"
]
.into_iter()
.try_map_err(|txt| {
let n = usize::from_str(&txt).map_err(|e| e.to_string())?;
if n < 4 {
Ok(n)
}
else {
Err("Too high".to_owned())
}
})
.collect();
assert_eq!(
mapped,
[
Ok(1),
Ok(2),
Ok(3),
Err("Too high".to_owned()),
Ok(5),
Err("invalid digit found in string".to_owned()),
Err("Too high".to_owned()),
]
);
Dyn Compatibility§
This trait is not dyn compatible.
In older versions of Rust, dyn compatibility was called "object safety", so this trait is not object safe.