MapOk / BoxOk
This crate provides the MapOk trait that allows mapping Ok variants in an iterator to a different type. Instead
of matching Result variants in a map call, you call
fn example() {
let input = ["10", "20", "x", "30"];
let mut iterator = input.into_iter().map(u32::from_str).map_ok(|x| x * 100);
}
instead of the more verbose
fn example() {
let input = ["10", "20", "x", "30"];
let mut iterator = input.into_iter().map(u32::from_str).map(|x| match x {
Ok(x) => Ok(x * 100),
Err(e) => Err(e),
});
}
Likewise, the box_ok function wraps the contents of the Ok variant into a Box, i.e. it behaves
like .map_ok(Box::new):
fn example() {
let input = ["10", "20", "x", "30"];
let results: Vec<Result<Box<u32>, ParseIntError>> = input
.into_iter()
.map(u32::from_str)
.map_ok(|x| x * 100)
.box_ok()
.collect();
}
Examples
Below is a worked example with a bit more involved parsing:
use std::num::ParseIntError;
use std::str::FromStr;
use map_ok::MapOk;
struct Person {
age: u8,
}
impl Person {
fn new(age: u8) -> Self {
Person { age }
}
}
impl FromStr for Person {
type Err = ParseIntError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
let age = u8::from_str(s)?;
Ok(Person::new(age))
}
}
fn example() {
let input = vec!["10", "20", "x", "30"];
let mut iterator = input.into_iter()
.map(Person::from_str)
.map_ok(|p| p.age);
assert_eq!(iterator.next(), Some(Ok(10)));
assert_eq!(iterator.next(), Some(Ok(20)));
assert!(iterator.next().unwrap().is_err());
assert_eq!(iterator.next(), Some(Ok(30)));
assert_eq!(iterator.next(), None);
}